diff --git a/lessons/c-c++/.archive/stage-2-original-20251105/level-1/lesson.md b/lessons/c-c++/.archive/stage-2-original-20251105/level-1/lesson.md index 604df55..754e650 100644 --- a/lessons/c-c++/.archive/stage-2-original-20251105/level-1/lesson.md +++ b/lessons/c-c++/.archive/stage-2-original-20251105/level-1/lesson.md @@ -26,7 +26,7 @@ Welcome to Stage 2! You've mastered copying code - now it's time to think like **Pseudocode** is a way to write programming logic in plain English (or your native language) before writing actual code. It's like writing a recipe or instructions for a task. **Example:** -```bash +``` Algorithm: Make a sandwich 1. Get bread from pantry 2. Get peanut butter from fridge @@ -35,7 +35,7 @@ Algorithm: Make a sandwich 5. Spread jelly on the other bread slice 6. Put slices together 7. Enjoy your sandwich! -```bash +``` This is much easier to understand than trying to write code first! @@ -50,13 +50,13 @@ This is much easier to understand than trying to write code first! ## Algorithm 1: Greeting Program **Pseudocode:** -```bash +``` Algorithm: Display Personal Greeting 1. Display "Hello! What's your name?" to the user 2. Get the user's name from input 3. Display "Nice to meet you, " followed by the user's name 4. Display "Welcome to programming!" -```bash +``` **Your Task:** Create a C program that follows these exact steps. @@ -65,7 +65,7 @@ Algorithm: Display Personal Greeting ## Algorithm 2: Simple Calculator **Pseudocode:** -```bash +``` Algorithm: Add Two Numbers 1. Ask user for first number 2. Get first number from user @@ -73,7 +73,7 @@ Algorithm: Add Two Numbers 4. Get second number from user 5. Calculate sum of the two numbers 6. Display "The sum is: " followed by the sum -```bash +``` **Your Task:** Create a C program that implements this calculator. @@ -82,14 +82,14 @@ Algorithm: Add Two Numbers ## Algorithm 3: Age Calculator **Pseudocode:** -```bash +``` Algorithm: Calculate Age in Days 1. Display "Enter your age in years: " 2. Get age in years from user 3. Calculate days = age × 365 4. Display "You are approximately " + days + " days old" 5. Display "That's a lot of days! " -```bash +``` **Your Task:** Create a program that calculates approximate age in days. @@ -98,7 +98,7 @@ Algorithm: Calculate Age in Days ## Algorithm 4: Temperature Converter **Pseudocode:** -```bash +``` Algorithm: Celsius to Fahrenheit Converter 1. Display "Enter temperature in Celsius: " 2. Get temperature in Celsius from user @@ -107,7 +107,7 @@ Algorithm: Celsius to Fahrenheit Converter 5. Display "°C = " 6. Display the Fahrenheit temperature 7. Display "°F" -```bash +``` **Your Task:** Create a temperature conversion program. @@ -116,7 +116,7 @@ Algorithm: Celsius to Fahrenheit Converter ## Algorithm 5: Rectangle Area Calculator **Pseudocode:** -```bash +``` Algorithm: Calculate Rectangle Area 1. Display "Rectangle Area Calculator" 2. Display "Enter length: " @@ -127,7 +127,7 @@ Algorithm: Calculate Rectangle Area 7. Calculate perimeter = 2 × (length + width) 8. Display "Area: " + area 9. Display "Perimeter: " + perimeter -```bash +``` **Your Task:** Create a program that calculates both area and perimeter. @@ -136,7 +136,7 @@ Algorithm: Calculate Rectangle Area ## Algorithm 6: Simple Interest Calculator **Pseudocode:** -```bash +``` Algorithm: Calculate Simple Interest 1. Display "Simple Interest Calculator" 2. Display "Enter principal amount: $" @@ -150,7 +150,7 @@ Algorithm: Calculate Simple Interest 10. Display "Principal: $" + principal 11. Display "Interest: $" + interest 12. Display "Total: $" + total -```bash +``` **Your Task:** Implement the complete interest calculation. @@ -211,7 +211,7 @@ Algorithm: Calculate Simple Interest ## Pseudocode Best Practices ### Good Pseudocode -```bash +``` Algorithm: Process User Data 1. Get user's name 2. Get user's age @@ -220,18 +220,18 @@ Algorithm: Process User Data Else Display "Minor user" 4. Display "Data processed" -```bash +``` ### Bad Pseudocode (Too Vague) -```bash +``` Algorithm: Do stuff 1. Get things 2. Calculate something 3. Show results -```bash +``` ### Good Pseudocode (Clear and Specific) -```bash +``` Algorithm: Calculate BMI 1. Display "BMI Calculator" 2. Display "Enter weight in kg: " @@ -240,7 +240,7 @@ Algorithm: Calculate BMI 5. Get height from user 6. Calculate BMI = weight ÷ (height × height) 7. Display "Your BMI is: " + BMI -```bash +``` --- @@ -266,7 +266,7 @@ int main() { return 0; } -```bash +``` **Key Concepts:** - [ ] `char name[50];` - String variable to store the name @@ -295,7 +295,7 @@ int main() { return 0; } -```bash +``` **Key Concepts:** - [ ] Multiple variables: `num1`, `num2`, `sum` @@ -322,7 +322,7 @@ int main() { return 0; } -```bash +``` **Key Concepts:** - [ ] Simple multiplication: `age_days = age_years * 365;` @@ -348,7 +348,7 @@ int main() { return 0; } -```bash +``` **Key Concepts:** - [ ] `float` variables for decimal temperatures @@ -380,7 +380,7 @@ int main() { return 0; } -```bash +``` **Key Concepts:** - [ ] Multiple calculations: area and perimeter @@ -416,7 +416,7 @@ int main() { return 0; } -```bash +``` **Key Concepts:** - [ ] Complex formula: `(principal * rate * time) / 100` @@ -471,28 +471,28 @@ int main() { int age; std::cout << "Enter age: "); scanf("%d", &age); -```bash +``` **Getting Decimals:** ```c float price; std::cout << "Enter price: $"); scanf("%f", &price); -```bash +``` **Getting Text:** ```c char name[50]; std::cout << "Enter name: "); scanf("%s", name); -```bash +``` **Displaying Results:** ```c std::cout << "Result: %d\n", result); std::cout << "Price: $%.2f\n", price); std::cout << "Hello, %s!\n", name); -```bash +``` --- @@ -530,7 +530,7 @@ Key functions and their purpose: ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/.archive/stage-2-original-20251105/level-2/lesson.md b/lessons/c-c++/.archive/stage-2-original-20251105/level-2/lesson.md index 6dc4e4e..13c717d 100644 --- a/lessons/c-c++/.archive/stage-2-original-20251105/level-2/lesson.md +++ b/lessons/c-c++/.archive/stage-2-original-20251105/level-2/lesson.md @@ -42,7 +42,7 @@ Variables are the memory of your programs! Today you'll learn how to use variabl ## Algorithm 1: Shopping Cart Total **Pseudocode:** -```cpp +``` Algorithm: Calculate Shopping Total 1. Initialize total to 0 2. Initialize item_count to 0 @@ -55,7 +55,7 @@ Algorithm: Calculate Shopping Total d. Get next price from user 6. Display "Items purchased: " + item_count 7. Display "Total cost: $" + total -```cpp +``` **Variable Analysis:** - [ ] `total`: Accumulator (starts at 0, adds prices) @@ -69,7 +69,7 @@ Algorithm: Calculate Shopping Total ## Algorithm 2: Password Validation **Pseudocode:** -```cpp +``` Algorithm: Validate Password 1. Initialize attempts to 0 2. Initialize is_valid to false @@ -84,7 +84,7 @@ Algorithm: Validate Password a. Display "Access granted! " 6. Else: a. Display "Access denied! " -```cpp +``` **Variable Analysis:** - [ ] `attempts`: Counter (tracks login attempts) @@ -99,7 +99,7 @@ Algorithm: Validate Password ## Algorithm 3: Grade Average Calculator **Pseudocode:** -```cpp +``` Algorithm: Calculate Class Average 1. Initialize total_score to 0 2. Initialize student_count to 0 @@ -118,7 +118,7 @@ Algorithm: Calculate Class Average c. Display "Total students: " + student_count 6. Else: a. Display "No students entered" -```cpp +``` **Variable Analysis:** - [ ] `total_score`: Accumulator (sums all grades) @@ -134,7 +134,7 @@ Algorithm: Calculate Class Average ## Algorithm 4: Number Guessing Game **Pseudocode:** -```cpp +``` Algorithm: Number Guessing Game 1. Initialize secret_number to 42 2. Initialize guess_count to 0 @@ -153,7 +153,7 @@ Algorithm: Number Guessing Game ii. Else: i. Display "Too low! Try higher." 6. Display "Thanks for playing!" -```cpp +``` **Variable Analysis:** - [ ] `secret_number`: Constant (game target) @@ -168,7 +168,7 @@ Algorithm: Number Guessing Game ## Algorithm 5: Bank Account Simulator **Pseudocode:** -```cpp +``` Algorithm: Bank Account Manager 1. Initialize balance to 1000.00 2. Initialize transaction_count to 0 @@ -201,7 +201,7 @@ Algorithm: Bank Account Manager g. Else: i. Display "Invalid choice!" 7. Display "Thank you for banking with us!" -```cpp +``` **Variable Analysis:** - [ ] `balance`: Accumulator (changes with deposits/withdrawals) @@ -217,7 +217,7 @@ Algorithm: Bank Account Manager ## Algorithm 6: Temperature Tracker **Pseudocode:** -```cpp +``` Algorithm: Daily Temperature Tracker 1. Initialize day_count to 0 2. Initialize total_temperature to 0 @@ -240,7 +240,7 @@ Algorithm: Daily Temperature Tracker 11. Display "Highest: " + highest_temp + "°F" 12. Display "Lowest: " + lowest_temp + "°F" 13. Display "Readings taken: " + reading_count -```cpp +``` **Variable Analysis:** - [ ] `total_temperature`: Accumulator (sum of all readings) @@ -258,7 +258,7 @@ Algorithm: Daily Temperature Tracker **For each algorithm, track how variables change:** **Example for Algorithm 1:** -```cpp +``` Initial state: total = 0, item_count = 0 @@ -273,7 +273,7 @@ total = 15.75, item_count = 2 User enters: 0 (finish) Final state: total = 15.75, item_count = 2 -```cpp +``` --- @@ -306,25 +306,25 @@ total = 15.75, item_count = 2 ## Variable Patterns in Pseudocode ### Counter Variables -```cpp +``` Initialize counter to 0 While condition: Add 1 to counter // do something Display "Count: " + counter -```cpp +``` ### Accumulator Variables -```cpp +``` Initialize total to 0 While getting values: Get value from user Add value to total Display "Total: " + total -```cpp +``` ### Flag Variables -```cpp +``` Initialize is_valid to false // check conditions If condition met: @@ -333,16 +333,16 @@ If is_valid: Display "Success" Else: Display "Failed" -```cpp +``` ### Tracker Variables -```cpp +``` Initialize maximum to smallest possible value Initialize minimum to largest possible value For each value: If value > maximum: set maximum to value If value < minimum: set minimum to value -```cpp +``` --- @@ -378,7 +378,7 @@ int main() { return 0; } -```cpp +``` **Variable Flow:** - [ ] `total`: Starts at 0, accumulates prices @@ -418,7 +418,7 @@ int main() { return 0; } -```cpp +``` **Key Concepts:** - [ ] String comparison with `strcmp()` @@ -460,7 +460,7 @@ int main() { return 0; } -```cpp +``` **Variable Management:** - [ ] `total_score`: Accumulates all grades @@ -504,7 +504,7 @@ int main() { return 0; } -```cpp +``` **Game Logic:** - [ ] `game_won` flag controls the game loop @@ -563,7 +563,7 @@ int main() { return 0; } -```cpp +``` **Complex Variable Management:** - [ ] `balance`: Changes with deposits/withdrawals @@ -614,7 +614,7 @@ int main() { return 0; } -```cpp +``` **Statistical Tracking:** - [ ] `highest_temp`: Tracks maximum value (initialized to very low) @@ -628,27 +628,27 @@ int main() { **Counters:** Always start at 0 ```c int count = 0; -```cpp +``` **Accumulators:** Usually start at 0 ```c float total = 0.0; -```cpp +``` **Flags:** Initialize to false/0 ```c int is_done = 0; -```cpp +``` **Maximum Trackers:** Initialize to minimum possible value ```c int max_value = INT_MIN; // or a very small number -```cpp +``` **Minimum Trackers:** Initialize to maximum possible value ```c int min_value = INT_MAX; // or a very large number -```cpp +``` ### Common Variable Mistakes @@ -656,13 +656,13 @@ int min_value = INT_MAX; // or a very large number ```c int sum; // Uninitialized - contains garbage value sum = sum + 5; // Undefined behavior! -```cpp +``` **Wrong Data Types:** ```c int average; // Wrong! Should be float for decimals average = 85.5; // Gets truncated to 85 -```cpp +``` **Scope Issues:** ```c @@ -670,7 +670,7 @@ if (condition) { int temp = 5; // Only exists in this block } // temp is undefined here! -```cpp +``` --- @@ -708,7 +708,7 @@ Key functions and their purpose: ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/.archive/stage-2-original-20251105/level-3/lesson.md b/lessons/c-c++/.archive/stage-2-original-20251105/level-3/lesson.md index 2794008..7d817ab 100644 --- a/lessons/c-c++/.archive/stage-2-original-20251105/level-3/lesson.md +++ b/lessons/c-c++/.archive/stage-2-original-20251105/level-3/lesson.md @@ -42,7 +42,7 @@ Mathematics is the language of algorithms! Today you'll translate mathematical c ## Algorithm 1: Geometry Calculator **Pseudocode:** -```cpp +``` Algorithm: Calculate Circle Properties 1. Display "Circle Calculator" 2. Display "Enter radius: " @@ -54,7 +54,7 @@ Algorithm: Calculate Circle Properties 8. Display "Diameter: " + diameter 9. Display "Area: " + area 10. Display "Circumference: " + circumference -```cpp +``` **Mathematical Notes:** - [ ] π (pi) ≈ 3.14159 @@ -69,7 +69,7 @@ Algorithm: Calculate Circle Properties ## Algorithm 2: Right Triangle Solver **Pseudocode:** -```cpp +``` Algorithm: Solve Right Triangle 1. Display "Right Triangle Calculator" 2. Display "Enter side A: " @@ -84,7 +84,7 @@ Algorithm: Solve Right Triangle 11. Display "Hypotenuse: " + hypotenuse 12. Display "Area: " + area 13. Display "Perimeter: " + perimeter -```cpp +``` **Mathematical Notes:** - [ ] Pythagorean theorem: c² = a² + b² (where c is hypotenuse) @@ -98,7 +98,7 @@ Algorithm: Solve Right Triangle ## Algorithm 3: Compound Interest Calculator **Pseudocode:** -```cpp +``` Algorithm: Calculate Compound Interest 1. Display "Compound Interest Calculator" 2. Display "Enter principal amount: $" @@ -117,7 +117,7 @@ Algorithm: Calculate Compound Interest 15. Display "Principal: $" + principal 16. Display "Final Amount: $" + final_amount 17. Display "Total Interest: $" + total_interest -```cpp +``` **Mathematical Notes:** - [ ] Compound interest formula: A = P(1 + r/n)^(nt) @@ -131,7 +131,7 @@ Algorithm: Calculate Compound Interest ## Algorithm 4: Quadratic Equation Solver **Pseudocode:** -```cpp +``` Algorithm: Solve Quadratic Equation 1. Display "Quadratic Equation Solver" 2. Display "For equation ax² + bx + c = 0" @@ -152,7 +152,7 @@ Algorithm: Solve Quadratic Equation 12. Else: a. Display "No real roots (complex solutions)" 13. Display "Discriminant: " + discriminant -```cpp +``` **Mathematical Notes:** - [ ] Quadratic formula: x = [-b ± √(b² - 4ac)] / 2a @@ -166,7 +166,7 @@ Algorithm: Solve Quadratic Equation ## Algorithm 5: Fibonacci Sequence Generator **Pseudocode:** -```cpp +``` Algorithm: Generate Fibonacci Sequence 1. Display "Fibonacci Sequence Generator" 2. Display "Enter number of terms: " @@ -186,7 +186,7 @@ Algorithm: Generate Fibonacci Sequence d. Set second = next e. Add 1 to count 11. Display "Sequence complete" -```cpp +``` **Mathematical Notes:** - [ ] Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, ... @@ -200,7 +200,7 @@ Algorithm: Generate Fibonacci Sequence ## Algorithm 6: Statistical Calculator **Pseudocode:** -```cpp +``` Algorithm: Calculate Statistics 1. Display "Statistical Calculator" 2. Initialize sum = 0 @@ -226,7 +226,7 @@ Algorithm: Calculate Statistics g. Display "Standard Deviation: " + standard_deviation 8. Else: a. Display "No numbers entered" -```cpp +``` **Mathematical Notes:** - [ ] Mean (average): μ = Σx / n @@ -241,7 +241,7 @@ Algorithm: Calculate Statistics ## Algorithm 7: Distance Calculator (Coordinate Geometry) **Pseudocode:** -```cpp +``` Algorithm: Calculate Distance Between Points 1. Display "Distance Between Two Points" 2. Display "Enter coordinates for point 1:" @@ -260,7 +260,7 @@ Algorithm: Calculate Distance Between Points 15. Display "Point 1: (" + x1 + ", " + y1 + ")" 16. Display "Point 2: (" + x2 + ", " + y2 + ")" 17. Display "Distance: " + distance -```cpp +``` **Mathematical Notes:** - [ ] Distance formula: d = √[(x₂ - x₁)² + (y₂ - y₁)²] @@ -277,7 +277,7 @@ Algorithm: Calculate Distance Between Points ```c # include # include // For mathematical functions -```cpp +``` **Common Math Functions:** - [ ] `sqrt(x)` - Square root @@ -370,7 +370,7 @@ int main() { return 0; } -```cpp +``` **Key Concepts:** - [ ] Constant PI defined as `const float` @@ -406,7 +406,7 @@ int main() { return 0; } -```cpp +``` **Key Concepts:** - [ ] `#include ` for `sqrt()` function @@ -448,7 +448,7 @@ int main() { return 0; } -```cpp +``` **Key Concepts:** - [ ] Complex compound interest formula @@ -492,7 +492,7 @@ int main() { return 0; } -```cpp +``` **Key Concepts:** - [ ] Discriminant determines number of roots @@ -535,7 +535,7 @@ int main() { return 0; } -```cpp +``` **Key Concepts:** - [ ] Iterative Fibonacci calculation @@ -584,7 +584,7 @@ int main() { return 0; } -```cpp +``` **Key Concepts:** - [ ] Statistical formulas implementation @@ -625,7 +625,7 @@ int main() { return 0; } -```cpp +``` **Key Concepts:** - [ ] Distance formula implementation @@ -641,7 +641,7 @@ int main() { const float PI = 3.14159265359; const float E = 2.71828182846; const float GRAVITY = 9.80665; -```cpp +``` **Precision Considerations:** - [ ] Use `double` for high-precision calculations @@ -657,7 +657,7 @@ result = 2 + 3 * 4; // Correct: (2 + 3) * 4 = 20 (parentheses force addition first) result = (2 + 3) * 4; -```cpp +``` **Integer Division:** ```c @@ -666,7 +666,7 @@ float result = 5 / 2; // Correct: 5.0 / 2 = 2.5 (float division) float result = 5.0 / 2; -```cpp +``` **Power Operations:** ```c @@ -675,7 +675,7 @@ result = 2 ^ 3; // Bitwise XOR, not power! // Correct: Use pow() function result = pow(2, 3); // 2^3 = 8 -```cpp +``` --- @@ -713,7 +713,7 @@ Key functions and their purpose: ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/.archive/stage-2-original-20251105/level-4/lesson.md b/lessons/c-c++/.archive/stage-2-original-20251105/level-4/lesson.md index 07a03b7..81b1fe7 100644 --- a/lessons/c-c++/.archive/stage-2-original-20251105/level-4/lesson.md +++ b/lessons/c-c++/.archive/stage-2-original-20251105/level-4/lesson.md @@ -31,7 +31,7 @@ User interaction is the heart of useful programs! Today you'll master the art of ## Algorithm 1: Age Verification System **Pseudocode:** -```cpp +``` Algorithm: Verify User Age 1. Display "=== Age Verification System ===" 2. Initialize is_valid_age to false @@ -51,7 +51,7 @@ Algorithm: Verify User Age a. Display " You are an adult!" 6. Else: a. Display " You are a minor." -```cpp +``` **Input/Output Focus:** - [ ] Input validation (numeric, range checking) @@ -66,7 +66,7 @@ Algorithm: Verify User Age ## Algorithm 2: Restaurant Menu System **Pseudocode:** -```cpp +``` Algorithm: Restaurant Ordering System 1. Display "=== Welcome to Code Café ===" 2. Initialize total_cost to 0 @@ -103,7 +103,7 @@ Algorithm: Restaurant Ordering System 9. Display "Tax (8%): $" + tax 10. Display "Final total: $" + final_total 11. Display "Thank you for your order! " -```cpp +``` **Input/Output Focus:** - [ ] Clear menu formatting @@ -118,7 +118,7 @@ Algorithm: Restaurant Ordering System ## Algorithm 3: Student Grade Manager **Pseudocode:** -```cpp +``` Algorithm: Student Grade Management 1. Display "=== Student Grade Manager ===" 2. Initialize grades array (can hold 100 grades) @@ -177,7 +177,7 @@ Algorithm: Student Grade Management i. Else: i. Display " Invalid choice! Please select 1-5." 6. Display "Thank you for using Grade Manager! " -```cpp +``` **Input/Output Focus:** - [ ] Array data storage @@ -192,7 +192,7 @@ Algorithm: Student Grade Management ## Algorithm 4: Unit Converter **Pseudocode:** -```cpp +``` Algorithm: Unit Conversion Calculator 1. Display "=== Unit Converter ===" 2. Initialize is_running to true @@ -248,7 +248,7 @@ Algorithm: Unit Conversion Calculator h. Else: i. Display " Invalid conversion type!" 4. Display "Thank you for using Unit Converter! " -```cpp +``` **Input/Output Focus:** - [ ] Nested menu systems @@ -263,7 +263,7 @@ Algorithm: Unit Conversion Calculator ## Algorithm 5: Survey Data Collector **Pseudocode:** -```cpp +``` Algorithm: Customer Satisfaction Survey 1. Display "=== Customer Satisfaction Survey ===" 2. Initialize responses array (can hold 50 responses) @@ -301,7 +301,7 @@ Algorithm: Customer Satisfaction Survey 7. Else: a. Display "No survey responses collected." 8. Display "Thank you for participating! " -```cpp +``` **Input/Output Focus:** - [ ] Clear survey instructions @@ -316,7 +316,7 @@ Algorithm: Customer Satisfaction Survey ## Algorithm 6: Library Book Tracker **Pseudocode:** -```cpp +``` Algorithm: Library Book Management 1. Display "=== Library Book Tracker ===" 2. Initialize books array (can hold 20 book titles) @@ -381,7 +381,7 @@ Algorithm: Library Book Management i. Else: i. Display " Invalid choice!" 6. Display "Thank you for using Library Book Tracker! " -```cpp +``` **Input/Output Focus:** - [ ] String array management @@ -403,7 +403,7 @@ if (input >= min_value && input <= max_value) { } else { // Invalid input - show error } -```cpp +``` **String Input Validation:** ```c @@ -413,7 +413,7 @@ if (strlen(input_string) > 0) { } else { // Empty input - show error } -```cpp +``` --- @@ -448,7 +448,7 @@ if (strlen(input_string) > 0) { ## User Interface Design Principles ### Clear Menu Design -```cpp +``` === Main Menu === 1. Add Item - Add new item to collection 2. View Items - Display all items @@ -457,7 +457,7 @@ if (strlen(input_string) > 0) { 5. Exit - Quit the program Enter choice (1-5): -```cpp +``` ### Error Message Best Practices - [ ] **Be specific**: "Grade must be between 0-100" not "Invalid input" @@ -516,7 +516,7 @@ int main() { return 0; } -```cpp +``` **Key Concepts:** - [ ] Input validation with `scanf()` return value checking @@ -584,7 +584,7 @@ int main() { return 0; } -```cpp +``` **Key Concepts:** - [ ] Switch statement for menu handling @@ -685,7 +685,7 @@ int main() { return 0; } -```cpp +``` **Key Concepts:** - [ ] Array storage for multiple grades @@ -768,7 +768,7 @@ int main() { return 0; } -```cpp +``` **Key Concepts:** - [ ] Nested menu system @@ -843,7 +843,7 @@ int main() { return 0; } -```cpp +``` **Key Concepts:** - [ ] Array storage for survey responses @@ -970,7 +970,7 @@ int main() { return 0; } -```cpp +``` **Key Concepts:** - [ ] 2D array for string storage @@ -988,7 +988,7 @@ int main() { // After scanf, clear remaining input int c; while ((c = getchar()) != '\n' && c != EOF); -```cpp +``` **Reading Full Lines:** ```c @@ -996,7 +996,7 @@ char buffer[100]; fgets(buffer, sizeof(buffer), stdin); // Remove trailing newline buffer[strcspn(buffer, "\n")] = '\0'; -```cpp +``` **Input Validation Patterns:** ```c @@ -1012,7 +1012,7 @@ int get_valid_number(int min, int max) { } while (value < min || value > max); return value; } -```cpp +``` --- @@ -1050,7 +1050,7 @@ Key functions and their purpose: ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/.archive/stage-2-original-20251105/level-5/lesson.md b/lessons/c-c++/.archive/stage-2-original-20251105/level-5/lesson.md index 298765a..64001e6 100644 --- a/lessons/c-c++/.archive/stage-2-original-20251105/level-5/lesson.md +++ b/lessons/c-c++/.archive/stage-2-original-20251105/level-5/lesson.md @@ -48,7 +48,7 @@ Decision-making is the intelligence of programs! Today you'll master complex con ## Algorithm 1: Loan Approval System **Pseudocode:** -```cpp +``` Algorithm: Evaluate Loan Application 1. Display "=== Loan Approval System ===" 2. Display "Enter applicant's age: " @@ -97,7 +97,7 @@ Algorithm: Evaluate Loan Application 22. Else: a. Display " LOAN DENIED" b. Display "Reason: " + approval_status -```cpp +``` **Decision Logic:** - [ ] Age restrictions (18-70) @@ -113,7 +113,7 @@ Algorithm: Evaluate Loan Application ## Algorithm 2: Health Risk Assessment **Pseudocode:** -```cpp +``` Algorithm: Assess Health Risk Factors 1. Display "=== Health Risk Assessment ===" 2. Display "Enter your age: " @@ -172,7 +172,7 @@ Algorithm: Assess Health Risk Factors 37. Else: a. Display " LOW RISK - Maintain healthy lifestyle" b. Display "Recommendations: Continue current healthy habits" -```cpp +``` **Decision Logic:** - [ ] Multi-factor risk assessment @@ -187,7 +187,7 @@ Algorithm: Assess Health Risk Factors ## Algorithm 3: Academic Standing Calculator **Pseudocode:** -```cpp +``` Algorithm: Determine Academic Standing 1. Display "=== Academic Standing Calculator ===" 2. Display "Enter GPA (0.0-4.0): " @@ -237,7 +237,7 @@ Algorithm: Determine Academic Standing a. Display " Limited eligibility - Academic plan required" 23. Else: a. Display " Counseling required - Contact academic advisor" -```cpp +``` **Decision Logic:** - [ ] Multi-criteria academic evaluation @@ -252,7 +252,7 @@ Algorithm: Determine Academic Standing ## Algorithm 4: Insurance Premium Calculator **Pseudocode:** -```cpp +``` Algorithm: Calculate Insurance Premium 1. Display "=== Auto Insurance Premium Calculator ===" 2. Display "Enter driver's age: " @@ -306,7 +306,7 @@ Algorithm: Calculate Insurance Premium 36. Else: a. Display " LOW RISK PROFILE" b. Display "Eligible for premium discounts" -```cpp +``` **Decision Logic:** - [ ] Multi-factor risk assessment @@ -321,7 +321,7 @@ Algorithm: Calculate Insurance Premium ## Algorithm 5: Travel Itinerary Planner **Pseudocode:** -```cpp +``` Algorithm: Plan Travel Itinerary 1. Display "=== Travel Itinerary Planner ===" 2. Display "Enter destination city: " @@ -385,7 +385,7 @@ Algorithm: Plan Travel Itinerary a. Display " Budget exceeded by $" + (total_budget - daily_budget × trip_days) 38. Else: a. Display " Within budget - $" + (daily_budget × trip_days - total_budget) + " remaining" -```cpp +``` **Decision Logic:** - [ ] Seasonal activity recommendations @@ -400,7 +400,7 @@ Algorithm: Plan Travel Itinerary ## Algorithm 6: Employee Performance Review **Pseudocode:** -```cpp +``` Algorithm: Evaluate Employee Performance 1. Display "=== Employee Performance Review ===" 2. Display "Enter employee name: " @@ -460,7 +460,7 @@ Algorithm: Evaluate Employee Performance 31. Else: a. Display " Performance review complete" b. Display "Continue professional development" -```cpp +``` **Decision Logic:** - [ ] Multi-criteria performance evaluation @@ -475,7 +475,7 @@ Algorithm: Evaluate Employee Performance ### Decision Tree Patterns **Eligibility Checking:** -```cpp +``` If primary_condition AND secondary_condition: If qualifying_factor: APPROVE @@ -483,19 +483,19 @@ If primary_condition AND secondary_condition: DENY Else: DENY -```cpp +``` **Risk Assessment:** -```cpp +``` Initialize risk_score = 0 For each risk_factor: If factor_present: Add points to risk_score Categorize based on total_score -```cpp +``` **Multi-tier Classification:** -```cpp +``` If score >= threshold_A: If sub_condition: CATEGORY_A_PLUS @@ -505,7 +505,7 @@ Else if score >= threshold_B: CATEGORY_B Else: CATEGORY_C -```cpp +``` --- @@ -553,7 +553,7 @@ ApplicationState evaluate_application(ApplicationData data) { if (data.income > 50000 && data.score > 700) return STATE_APPROVED; return STATE_PROCESSING; } -```cpp +``` ### Rule Engine Pattern ```c @@ -566,7 +566,7 @@ int evaluate_rules(DataItem item, Rule* rules, int rule_count) { } return score; } -```cpp +``` ### Decision Table Pattern ```c @@ -576,7 +576,7 @@ int evaluate_rules(DataItem item, Rule* rules, int rule_count) { // >=25| <30k | <600 | Deny // >=25| >=30k | >=600 | Approve // >=25| <30k | >=600 | Review -```cpp +``` --- @@ -654,7 +654,7 @@ int main() { return 0; } -```cpp +``` **Key Concepts:** - [ ] Complex nested conditional logic @@ -733,7 +733,7 @@ int main() { return 0; } -```cpp +``` **Key Concepts:** - [ ] Point-based risk assessment system @@ -812,7 +812,7 @@ int main() { return 0; } -```cpp +``` **Key Concepts:** - [ ] Multi-criteria academic evaluation @@ -890,7 +890,7 @@ int main() { return 0; } -```cpp +``` **Key Concepts:** - [ ] Cumulative risk multiplier system @@ -989,7 +989,7 @@ int main() { return 0; } -```cpp +``` **Key Concepts:** - [ ] Seasonal activity recommendations @@ -1078,7 +1078,7 @@ int main() { return 0; } -```cpp +``` **Key Concepts:** - [ ] Multi-criteria performance evaluation @@ -1105,7 +1105,7 @@ if (age >= 18) { } } } -```cpp +``` **Consistent Structure:** ```c @@ -1117,7 +1117,7 @@ if (condition1) { } else { // handle default case } -```cpp +``` **Early Returns:** ```c @@ -1127,7 +1127,7 @@ if (invalid_input) { return; } // continue with valid input -```cpp +``` --- @@ -1165,7 +1165,7 @@ Key functions and their purpose: ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/.archive/stage-2-original-20251105/level-6/lesson.md b/lessons/c-c++/.archive/stage-2-original-20251105/level-6/lesson.md index 61e3f82..f5bc649 100644 --- a/lessons/c-c++/.archive/stage-2-original-20251105/level-6/lesson.md +++ b/lessons/c-c++/.archive/stage-2-original-20251105/level-6/lesson.md @@ -48,7 +48,7 @@ Loops are the workhorses of programming! Today you'll master algorithms that use ## Algorithm 1: Sales Data Analyzer **Pseudocode:** -```cpp +``` Algorithm: Analyze Monthly Sales Data 1. Display "=== Sales Data Analyzer ===" 2. Initialize sales array (can hold 30 values) @@ -85,7 +85,7 @@ Algorithm: Analyze Monthly Sales Data i. Display "Day " + (i + 1) + ": $" + sales[i] 10. Else: a. Display "No sales data entered." -```cpp +``` **Loop Logic:** - [ ] Input loop with validation @@ -100,7 +100,7 @@ Algorithm: Analyze Monthly Sales Data ## Algorithm 2: Student Attendance Tracker **Pseudocode:** -```cpp +``` Algorithm: Track Class Attendance 1. Display "=== Class Attendance Tracker ===" 2. Display "Enter number of students: " @@ -133,7 +133,7 @@ Algorithm: Track Class Attendance i. Display "Student " + student + ": Present" b. Else: i. Display "Student " + student + ": Absent" -```cpp +``` **Loop Logic:** - [ ] Fixed iteration for known number of students @@ -148,7 +148,7 @@ Algorithm: Track Class Attendance ## Algorithm 3: Inventory Management System **Pseudocode:** -```cpp +``` Algorithm: Manage Store Inventory 1. Display "=== Inventory Management System ===" 2. Initialize item_names array (can hold 50 items) @@ -222,7 +222,7 @@ Algorithm: Manage Store Inventory i. Else: i. Display " Invalid choice!" 7. Display "Thank you for using Inventory Management System! " -```cpp +``` **Loop Logic:** - [ ] Menu-driven interface with multiple operations @@ -237,7 +237,7 @@ Algorithm: Manage Store Inventory ## Algorithm 4: Grade Book Calculator **Pseudocode:** -```cpp +``` Algorithm: Calculate Final Grades 1. Display "=== Grade Book Calculator ===" 2. Display "Enter number of students: " @@ -294,7 +294,7 @@ Algorithm: Calculate Final Grades 23. Display "C grades: " + grade_ranges[2] 24. Display "D grades: " + grade_ranges[3] 25. Display "F grades: " + grade_ranges[4] -```cpp +``` **Loop Logic:** - [ ] 2D array processing (nested loops) @@ -309,7 +309,7 @@ Algorithm: Calculate Final Grades ## Algorithm 5: Password Generator **Pseudocode:** -```cpp +``` Algorithm: Generate Secure Passwords 1. Display "=== Password Generator ===" 2. Display "Enter desired password length (8-20): " @@ -347,7 +347,7 @@ Algorithm: Generate Secure Passwords 23. If include_special is "y": a. Display " Special characters" 24. Display " Lowercase letters (always included)" -```cpp +``` **Loop Logic:** - [ ] Input validation loop @@ -362,7 +362,7 @@ Algorithm: Generate Secure Passwords ## Algorithm 6: Voting System **Pseudocode:** -```cpp +``` Algorithm: Conduct Election Voting 1. Display "=== Election Voting System ===" 2. Initialize candidate_names array ["Alice", "Bob", "Charlie"] @@ -407,7 +407,7 @@ Algorithm: Conduct Election Voting ii. Display candidate_names[i] + ": " + votes[i] + " votes (" + percentage + "%)" 8. Else: a. Display "No votes were cast." -```cpp +``` **Loop Logic:** - [ ] Menu-driven voting interface @@ -465,25 +465,25 @@ Algorithm: Conduct Election Voting ## Loop Algorithm Patterns ### Accumulation Pattern -```cpp +``` Initialize total to 0 While getting values: Get next_value Add next_value to total Display "Total: " + total -```cpp +``` ### Counting Pattern -```cpp +``` Initialize count to 0 For each item: If item meets criteria: Add 1 to count Display "Count: " + count -```cpp +``` ### Search Pattern -```cpp +``` Initialize found to false For each item in collection: If item matches target: @@ -494,10 +494,10 @@ If found: Display "Found at location" Else: Display "Not found" -```cpp +``` ### Validation Pattern -```cpp +``` Initialize is_valid to false While not is_valid: Get user_input @@ -506,7 +506,7 @@ While not is_valid: Else: Display error message Process valid input -```cpp +``` --- @@ -572,7 +572,7 @@ int main() { return 0; } -```cpp +``` **Key Concepts:** - [ ] Array storage for sales data @@ -638,7 +638,7 @@ int main() { return 0; } -```cpp +``` **Key Concepts:** - [ ] Fixed iteration for known number of students @@ -771,7 +771,7 @@ int main() { return 0; } -```cpp +``` **Key Concepts:** - [ ] 2D array for string storage @@ -871,7 +871,7 @@ int main() { return 0; } -```cpp +``` **Key Concepts:** - [ ] 2D array processing with nested loops @@ -963,7 +963,7 @@ int main() { return 0; } -```cpp +``` **Key Concepts:** - [ ] Input validation loop @@ -1052,7 +1052,7 @@ int main() { return 0; } -```cpp +``` **Key Concepts:** - [ ] Menu-driven voting interface @@ -1079,7 +1079,7 @@ for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) { if (array[i] > max) max = array[i]; } -```cpp +``` **Early Termination:** ```c @@ -1090,7 +1090,7 @@ for (int i = 0; i < size; i++) { break; // Don't continue searching } } -```cpp +``` --- @@ -1128,7 +1128,7 @@ Key functions and their purpose: ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/.archive/stage-2-original-20251105/level-7/lesson.md b/lessons/c-c++/.archive/stage-2-original-20251105/level-7/lesson.md index a4df975..d285484 100644 --- a/lessons/c-c++/.archive/stage-2-original-20251105/level-7/lesson.md +++ b/lessons/c-c++/.archive/stage-2-original-20251105/level-7/lesson.md @@ -48,7 +48,7 @@ Functions are the building blocks of organized code! Today you'll master algorit ## Algorithm 1: Calculator Program with Functions **Pseudocode:** -```cpp +``` Algorithm: Modular Calculator Program Function: display_menu() @@ -110,7 +110,7 @@ Main Algorithm: e. Else: i. Display " Invalid choice!" 3. Display "Thank you for using the calculator! " -```cpp +``` **Function Design:** - [ ] `display_menu()`: Handles UI display @@ -125,7 +125,7 @@ Main Algorithm: ## Algorithm 2: Student Grade Management System **Pseudocode:** -```cpp +``` Algorithm: Student Grade Management with Functions Function: display_main_menu() @@ -215,7 +215,7 @@ Main Algorithm: h. Else: i. Display " Invalid choice!" 6. Display "Thank you for using Grade Management System! " -```cpp +``` **Function Design:** - [ ] `display_main_menu()`: UI function @@ -231,7 +231,7 @@ Main Algorithm: ## Algorithm 3: Library Book System **Pseudocode:** -```cpp +``` Algorithm: Library Management System with Functions Function: display_library_menu() @@ -335,7 +335,7 @@ Main Algorithm: i. Else: i. Display " Invalid choice!" 7. Display "Thank you for using Library Management System! " -```cpp +``` **Function Design:** - [ ] `display_library_menu()`: UI function @@ -351,7 +351,7 @@ Main Algorithm: ## Algorithm 4: Math Quiz Game **Pseudocode:** -```cpp +``` Algorithm: Interactive Math Quiz with Functions Function: generate_question() @@ -421,7 +421,7 @@ Main Algorithm: g. Display blank line 7. Call display_score(correct_count, num_questions) 8. Display "Thanks for playing! " -```cpp +``` **Function Design:** - [ ] `generate_question()`: Random question creation @@ -438,7 +438,7 @@ Main Algorithm: ## Algorithm 5: Bank Account Manager **Pseudocode:** -```cpp +``` Algorithm: Bank Account Management with Functions Function: display_account_menu() @@ -525,7 +525,7 @@ Main Algorithm: h. Else: i. Display " Invalid choice!" 8. Display "Thank you for banking with us! " -```cpp +``` **Function Design:** - [ ] `display_account_menu()`: UI function @@ -541,7 +541,7 @@ Main Algorithm: ## Algorithm 6: Text Analyzer **Pseudocode:** -```cpp +``` Algorithm: Text Analysis Tool with Functions Function: count_words(text) @@ -621,7 +621,7 @@ Main Algorithm: 5. Else: a. Display " No text entered." 6. Display "Analysis complete! " -```cpp +``` **Function Design:** - [ ] `count_words()`: Word counting logic @@ -648,7 +648,7 @@ int validate_user_input(char* input); int calc(float x); void process(); int check(char* str); -```cpp +``` **Parameter Design:** ```c @@ -657,7 +657,7 @@ void transfer_money(Account* from, Account* to, float amount); // Bad - unclear what parameters do void process(float a, float b, int c); -```cpp +``` **Return Value Design:** ```c @@ -666,7 +666,7 @@ int save_file(const char* filename); // Returns 0 on success, -1 on error // Bad - unclear return meaning int do_something(); -```cpp +``` --- @@ -700,13 +700,13 @@ int do_something(); ## Function Architecture Patterns ### Layered Architecture -```cpp +``` Presentation Layer (UI functions) ↓ Business Logic Layer (processing functions) ↓ Data Access Layer (storage/retrieval functions) -```cpp +``` ### Pipeline Pattern ```c @@ -718,7 +718,7 @@ Result process_data(Input data) { data = format_output(data); return data; } -```cpp +``` ### Factory Pattern ```c @@ -730,7 +730,7 @@ Calculator* create_calculator(CalculationType type) { default: return NULL; } } -```cpp +``` --- @@ -829,7 +829,7 @@ int main() { std::cout << "Thank you for using the calculator! \n"); return 0; } -```cpp +``` **Key Concepts:** - [ ] Modular function design with single responsibilities @@ -972,7 +972,7 @@ int main() { std::cout << "Thank you for using Grade Management System! \n"); return 0; } -```cpp +``` **Key Concepts:** - [ ] Array parameters with pointers for modification @@ -1139,7 +1139,7 @@ int main() { std::cout << "Thank you for using Library Management System! \n"); return 0; } -```cpp +``` **Key Concepts:** - [ ] Complex string handling with fgets and newline removal @@ -1254,7 +1254,7 @@ int main() { return 0; } -```cpp +``` **Key Concepts:** - [ ] Random number generation for question creation @@ -1395,7 +1395,7 @@ int main() { std::cout << "Thank you for banking with us! \n"); return 0; } -```cpp +``` **Key Concepts:** - [ ] Financial transaction processing @@ -1530,7 +1530,7 @@ int main() { std::cout << "Analysis complete! \n"); return 0; } -```cpp +``` **Key Concepts:** - [ ] Text processing algorithms @@ -1594,7 +1594,7 @@ Key functions and their purpose: ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/.archive/stage-3-original-20251105/level-1/lesson.md b/lessons/c-c++/.archive/stage-3-original-20251105/level-1/lesson.md index bbd3d23..fc65c92 100644 --- a/lessons/c-c++/.archive/stage-3-original-20251105/level-1/lesson.md +++ b/lessons/c-c++/.archive/stage-3-original-20251105/level-1/lesson.md @@ -80,10 +80,10 @@ Create a program that asks the user for a temperature in Fahrenheit and classifi The program should display both the temperature and its classification. **Example:** -```cpp +``` Enter temperature in Fahrenheit: 75 Temperature: 75°F - Comfortable -```cpp +``` **Your Task:** 1. Write pseudocode for this problem @@ -103,13 +103,13 @@ Create a program that simulates a vending machine selling snacks for $1.50 each. - [ ] Handle cases where payment is insufficient **Example:** -```cpp +``` How many snacks would you like? 3 Total cost: $4.50 Enter payment amount: $5.00 Change: $0.50 Thank you for your purchase! -```cpp +``` **Your Task:** 1. Write pseudocode for this vending machine @@ -131,11 +131,11 @@ Create a program that asks for a person's age and determines their life stage ca Also display how many years until the next category (or "Final stage" if Senior). **Example:** -```cpp +``` Enter age: 25 Category: Young Adult Years until next category: 11 -```cpp +``` **Your Task:** 1. Write pseudocode for age categorization @@ -157,7 +157,7 @@ Create a program that calculates movie ticket prices based on: The program should ask for age, show time (24-hour format), and number of tickets. **Example:** -```cpp +``` Enter age: 70 Enter show time (0-23): 14 Enter number of tickets: 2 @@ -167,7 +167,7 @@ Senior discount: 30% off Matinee discount: 20% off Final price per ticket: $6.72 Total for 2 tickets: $13.44 -```cpp +``` **Your Task:** 1. Write pseudocode for ticket price calculation @@ -187,14 +187,14 @@ Create a program that asks the user for three numbers and: - [ ] Determines if the numbers form an increasing sequence **Example:** -```cpp +``` Enter three numbers: 5 8 3 Largest: 8 Smallest: 3 Average: 5.33 All equal: No Increasing sequence: No -```cpp +``` **Your Task:** 1. Write pseudocode for number analysis @@ -216,11 +216,11 @@ Create a program that converts a numerical grade (0-100) to a letter grade: Also display a motivational message based on the grade. **Example:** -```cpp +``` Enter numerical grade (0-100): 87 Letter grade: B Message: Good job! Keep up the excellent work! -```cpp +``` **Your Task:** 1. Write pseudocode for grade conversion @@ -232,17 +232,17 @@ Message: Good job! Keep up the excellent work! ### Pseudocode Writing Guidelines **Good Pseudocode Structure:** -```cpp +``` Algorithm: Problem Name 1. Clear step-by-step instructions 2. Handle all input/output 3. Include decision points 4. Handle edge cases 5. End with clear output -```cpp +``` **Example:** -```cpp +``` Algorithm: Temperature Classifier 1. Display "Enter temperature in Fahrenheit: " 2. Get temperature from user @@ -256,7 +256,7 @@ Algorithm: Temperature Classifier a. Display temperature + "°F - Warm" 7. Else: a. Display temperature + "°F - Hot" -```cpp +``` --- @@ -327,7 +327,7 @@ Algorithm: Temperature Classifier - [ ] Edge cases: Negative temperatures, very high temperatures **Sample Pseudocode:** -```cpp +``` Algorithm: Temperature Classifier 1. Display "Enter temperature in Fahrenheit: " 2. Get temperature from user @@ -341,7 +341,7 @@ Algorithm: Temperature Classifier a. Display temperature + "°F - Warm" 7. Else: a. Display temperature + "°F - Hot" -```cpp +``` **Test Cases:** - [ ] 25°F → Freezing @@ -361,7 +361,7 @@ Algorithm: Temperature Classifier - [ ] Constants: Snack price = $1.50 **Sample Pseudocode:** -```cpp +``` Algorithm: Vending Machine 1. Set snack_price to 1.50 2. Display "How many snacks would you like? " @@ -377,7 +377,7 @@ Algorithm: Vending Machine 9. Else: a. Calculate needed = total_cost - payment b. Display "Insufficient payment. You need $" + needed + " more." -```cpp +``` --- @@ -447,23 +447,23 @@ Algorithm: Vending Machine ### Common Problem-Solving Patterns **Range Checking:** -```cpp +``` If value >= min AND value <= max: Process valid value Else: Handle invalid value -```cpp +``` **Sequential Processing:** -```cpp +``` Step 1: Get input Step 2: Validate input Step 3: Process data Step 4: Display results -```cpp +``` **Decision Trees:** -```cpp +``` If condition A: If sub-condition A1: Action A1 @@ -473,7 +473,7 @@ Else if condition B: Action B Else: Default action -```cpp +``` --- @@ -539,7 +539,7 @@ Expected implementation provided. ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/.archive/stage-3-original-20251105/level-2/lesson.md b/lessons/c-c++/.archive/stage-3-original-20251105/level-2/lesson.md index deeef34..f369e43 100644 --- a/lessons/c-c++/.archive/stage-3-original-20251105/level-2/lesson.md +++ b/lessons/c-c++/.archive/stage-3-original-20251105/level-2/lesson.md @@ -66,7 +66,7 @@ Create a program that manages student grades for a class. The program should: - [ ] Search/filter capabilities **Example Usage:** -```cpp +``` 1. Add Student 2. View All Students 3. Show Statistics @@ -83,7 +83,7 @@ Class Statistics: Average: 87.5% Highest: 95% (Alice) Lowest: 80% (Bob) -```cpp +``` **Your Task:** 1. Design data structures for student information @@ -110,7 +110,7 @@ Create an inventory management system for a small store with: - [ ] Search functionality **Example Usage:** -```cpp +``` Inventory System: 1. Add Product 2. Update Stock @@ -129,7 +129,7 @@ Choice: 4 Low Stock Alert: - [ ] Mouse: 3 units remaining - [ ] Keyboard: 2 units remaining -```cpp +``` **Your Task:** 1. Design product data structure @@ -158,7 +158,7 @@ Build a digital address book that can: - [ ] Contact management operations **Example Usage:** -```cpp +``` Contact Manager: 1. Add Contact 2. Search Contact @@ -175,7 +175,7 @@ Contact added! Choice: 2 Enter search name: John Found: John Doe - (555) 123-4567 - john@example.com -```cpp +``` **Your Task:** 1. Design contact data structure @@ -203,7 +203,7 @@ Create a library system that tracks: - [ ] Statistical reporting **Example Usage:** -```cpp +``` Library System: 1. Add Book 2. Search Books @@ -218,7 +218,7 @@ Total Books: 150 Available: 120 Checked Out: 30 Most Popular Author: J.K. Rowling (8 books) -```cpp +``` **Your Task:** 1. Design book database structure @@ -247,7 +247,7 @@ Build a personal finance tracker that: - [ ] Financial calculations and summaries **Example Usage:** -```cpp +``` Expense Tracker: 1. Add Expense 2. View by Category @@ -263,7 +263,7 @@ Entertainment: $89.99 Utilities: $200.00 Other: $50.25 Total: $910.74 -```cpp +``` **Your Task:** 1. Design expense data structure @@ -292,7 +292,7 @@ Create a to-do list manager that can: - [ ] Search and filter capabilities **Example Usage:** -```cpp +``` Task Manager: 1. Add Task 2. Complete Task @@ -309,7 +309,7 @@ High Priority Tasks: Medium Priority Tasks: 1. Buy groceries (Completed) 2. Clean room (Not completed) -```cpp +``` **Your Task:** 1. Design task data structure @@ -334,7 +334,7 @@ Medium Priority Tasks: - [ ] **Consider access patterns** (how data will be used) **Example Design:** -```cpp +``` Student Grade Book: - [ ] student_names[100][50] - array of strings - [ ] student_grades[100] - array of floats @@ -342,7 +342,7 @@ Student Grade Book: Each student[i] corresponds to: - [ ] student_names[i] and student_grades[i] -```cpp +``` --- @@ -380,7 +380,7 @@ Each student[i] corresponds to: ## Data Management Patterns ### Array Management -```cpp +``` Initialize array and counter While adding items: If not at capacity: @@ -388,10 +388,10 @@ While adding items: Increment counter Else: Show capacity error -```cpp +``` ### Search Operations -```cpp +``` Initialize found flag to false For each item in collection: If item matches search criteria: @@ -399,19 +399,19 @@ For each item in collection: Set found flag to true If not found: Display "not found" message -```cpp +``` ### Data Validation -```cpp +``` When receiving input: Check if input is valid format Check if input is within acceptable range Check for required fields Show appropriate error messages -```cpp +``` ### Statistical Calculations -```cpp +``` Initialize accumulator variables For each data item: Add to running totals @@ -419,7 +419,7 @@ For each data item: Count valid items Calculate averages and percentages Display formatted results -```cpp +``` --- @@ -432,11 +432,11 @@ Display formatted results ### Problem 1: Student Grade Book **Data Structure Design:** -```cpp +``` student_names[25][50] - array of student names student_grades[25] - array of corresponding grades student_count - number of students currently stored -```cpp +``` **Key Operations:** - [ ] Add student: Validate grade range, store in next available slot @@ -455,12 +455,12 @@ student_count - number of students currently stored ### Problem 2: Inventory Tracker **Data Structure Design:** -```cpp +``` product_names[50][50] - product names product_prices[50] - product prices product_stock[50] - current stock levels product_count - number of products -```cpp +``` **Key Operations:** - [ ] Add product: Store name, price, initial stock @@ -479,12 +479,12 @@ product_count - number of products ### Problem 3: Contact List Manager **Data Structure Design:** -```cpp +``` contact_names[100][50] - contact names contact_phones[100][20] - phone numbers contact_emails[100][50] - email addresses contact_count - number of contacts -```cpp +``` **Key Operations:** - [ ] Add contact: Validate phone/email format, store all fields @@ -502,13 +502,13 @@ contact_count - number of contacts ### Problem 4: Library Book Database **Data Structure Design:** -```cpp +``` book_titles[200][100] - book titles book_authors[200][50] - author names book_isbns[200][20] - ISBN numbers book_available[200] - availability status (1=available, 0=checked out) book_count - number of books -```cpp +``` **Key Operations:** - [ ] Add book: Store all book information @@ -526,13 +526,13 @@ book_count - number of books ### Problem 5: Expense Tracker **Data Structure Design:** -```cpp +``` expense_dates[100][20] - expense dates (MM/DD/YYYY format) expense_descriptions[100][100] - expense descriptions expense_amounts[100] - expense amounts expense_categories[100] - category indices (0=Food, 1=Transportation, etc.) expense_count - number of expenses -```cpp +``` **Key Operations:** - [ ] Add expense: Store all expense details @@ -541,22 +541,22 @@ expense_count - number of expenses - [ ] Budget alerts: Compare against monthly budgets **Categories Array:** -```cpp +``` categories[5] = {"Food", "Transportation", "Entertainment", "Utilities", "Other"} -```cpp +``` --- ### Problem 6: Task Management System **Data Structure Design:** -```cpp +``` task_titles[50][100] - task titles task_descriptions[50][200] - task descriptions task_priorities[50] - priority levels (0=Low, 1=Medium, 2=High) task_completed[50] - completion status (0=pending, 1=completed) task_count - number of tasks -```cpp +``` **Key Operations:** - [ ] Add task: Store all task information @@ -566,12 +566,12 @@ task_count - number of tasks - [ ] Statistics: Completion rates, priority distribution **Priority Display:** -```cpp +``` High Priority: Show first (most important) Medium Priority: Show second Low Priority: Show last Completed tasks: Show with checkmark -```cpp +``` --- @@ -583,7 +583,7 @@ Completed tasks: Show with checkmark char names[MAX_ITEMS][50]; float values[MAX_ITEMS]; int count = 0; -```cpp +``` **Add One Operation at a Time:** 1. Implement data storage @@ -642,7 +642,7 @@ Expected implementation provided. ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/.archive/stage-3-original-20251105/level-3/lesson.md b/lessons/c-c++/.archive/stage-3-original-20251105/level-3/lesson.md index 807a24b..b0954c7 100644 --- a/lessons/c-c++/.archive/stage-3-original-20251105/level-3/lesson.md +++ b/lessons/c-c++/.archive/stage-3-original-20251105/level-3/lesson.md @@ -80,10 +80,10 @@ Create a program that calculates the nth Fibonacci number. The Fibonacci sequenc The program should ask for n and display the nth Fibonacci number. **Example:** -```cpp +``` Enter n: 8 Fibonacci number 8 is: 21 -```cpp +``` **Your Task:** 1. Write pseudocode for Fibonacci calculation @@ -98,15 +98,15 @@ Fibonacci number 8 is: 21 Create a program that determines if a given number is prime. A prime number is a positive integer greater than 1 that has no positive divisors other than 1 and itself. **Example:** -```cpp +``` Enter a number: 17 17 is a prime number. -```cpp +``` -```cpp +``` Enter a number: 15 15 is not a prime number. -```cpp +``` **Your Task:** 1. Write pseudocode for primality testing @@ -124,10 +124,10 @@ Create a program that calculates the factorial of a given number. Factorial of n - [ ] n! = n × (n-1) × (n-2) × ... × 1 **Example:** -```cpp +``` Enter n: 5 5! = 120 -```cpp +``` **Your Task:** 1. Write pseudocode for factorial calculation @@ -150,7 +150,7 @@ Where: - [ ] t = time in years **Example:** -```cpp +``` Enter principal amount: 1000 Enter annual interest rate (decimal): 0.05 Enter compounding frequency per year: 12 @@ -158,7 +158,7 @@ Enter time in years: 2 Final amount: $1104.54 Interest earned: $104.54 -```cpp +``` **Your Task:** 1. Write pseudocode for compound interest calculation @@ -180,14 +180,14 @@ Where: - [ ] n = number of terms **Example:** -```cpp +``` Enter first term: 3 Enter common difference: 2 Enter number of terms: 5 Series: 3, 5, 7, 9, 11 Sum: 35 -```cpp +``` **Your Task:** 1. Write pseudocode for arithmetic series sum @@ -204,11 +204,11 @@ Create a program that determines if a number is perfect. A perfect number is a p Example: 6 is perfect because 1 + 2 + 3 = 6 **Example:** -```cpp +``` Enter a number: 28 28 is a perfect number. Divisors: 1, 2, 4, 7, 14 (sum = 28) -```cpp +``` **Your Task:** 1. Write pseudocode for perfect number checking @@ -220,24 +220,24 @@ Divisors: 1, 2, 4, 7, 14 (sum = 28) ### Mathematical Pseudocode Guidelines **Formula Implementation:** -```cpp +``` Algorithm: Formula Calculator 1. Identify all variables in the formula 2. Determine the order of operations 3. Handle special cases (division by zero, etc.) 4. Calculate step by step 5. Display results with appropriate precision -```cpp +``` **Sequence Generation:** -```cpp +``` Algorithm: Sequence Generator 1. Initialize first terms 2. Use loop to generate subsequent terms 3. Apply the sequence rule 4. Store or display terms as needed 5. Handle termination conditions -```cpp +``` --- @@ -306,7 +306,7 @@ Algorithm: Sequence Generator - [ ] Efficiency: Iterative approach for large n **Sample Pseudocode:** -```cpp +``` Algorithm: Fibonacci Calculator 1. Display "Enter n: " 2. Get n from user @@ -321,7 +321,7 @@ Algorithm: Fibonacci Calculator ii. Set a = b iii. Set b = temp c. Display "Fibonacci number " + n + " is: " + b -```cpp +``` --- @@ -465,7 +465,7 @@ Expected implementation provided. ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/.archive/stage-3-original-20251105/level-4/lesson.md b/lessons/c-c++/.archive/stage-3-original-20251105/level-4/lesson.md index 1b3e78b..791a453 100644 --- a/lessons/c-c++/.archive/stage-3-original-20251105/level-4/lesson.md +++ b/lessons/c-c++/.archive/stage-3-original-20251105/level-4/lesson.md @@ -84,7 +84,7 @@ Create an interactive calculator program with a menu that allows users to: The program should display a menu, get user choice, perform the selected operation, and return to the menu until the user chooses to exit. **Example:** -```cpp +``` === Calculator Menu === 1. Addition 2. Subtraction @@ -98,7 +98,7 @@ Enter second number: 5 Result: 10 + 5 = 15 Press Enter to continue... -```cpp +``` **Your Task:** 1. Write pseudocode for menu-driven calculator @@ -120,7 +120,7 @@ Create a banking system menu that allows users to: Maintain a balance and track transactions. Handle insufficient funds for withdrawals. **Example:** -```cpp +``` === Banking Menu === 1. Check Balance 2. Deposit @@ -133,7 +133,7 @@ Enter deposit amount: 100 Deposit successful! New balance: $100.00 Press Enter to continue... -```cpp +``` **Your Task:** 1. Write pseudocode for banking system @@ -155,7 +155,7 @@ Create a student grade management system with menu options: Store up to 10 student names and grades. Handle cases where no grades are entered. **Example:** -```cpp +``` === Grade Manager === 1. Add Student Grade 2. View All Grades @@ -169,7 +169,7 @@ Enter grade (0-100): 95 Grade added successfully! Press Enter to continue... -```cpp +``` **Your Task:** 1. Write pseudocode for grade management @@ -192,7 +192,7 @@ Create a restaurant menu system with: Include at least 5 menu items with prices. Allow multiple items in one order. **Example:** -```cpp +``` === Restaurant Menu === 1. View Menu 2. Place Order @@ -210,7 +210,7 @@ Enter choice: 1 5. Dessert - $4.99 Press Enter to continue... -```cpp +``` **Your Task:** 1. Write pseudocode for restaurant ordering @@ -233,7 +233,7 @@ Create a library book management system with: Track book availability and borrower names. Handle cases where books are not available. **Example:** -```cpp +``` === Library System === 1. Add Book 2. Search Books @@ -248,7 +248,7 @@ Enter author: Kernighan & Ritchie Book added successfully! Press Enter to continue... -```cpp +``` **Your Task:** 1. Write pseudocode for library system @@ -270,7 +270,7 @@ Create a simple game menu system with: Include a number guessing game for "Start New Game". Track high scores and allow basic settings. **Example:** -```cpp +``` === Game Menu === 1. Start New Game 2. Load Game @@ -287,7 +287,7 @@ Too low! Try again: 37 Correct! You won in 3 guesses! Press Enter to continue... -```cpp +``` **Your Task:** 1. Write pseudocode for game menu system @@ -299,7 +299,7 @@ Press Enter to continue... ### Interactive Pseudocode Guidelines **Menu System Structure:** -```cpp +``` Algorithm: Menu System 1. Display menu options clearly 2. Get user choice @@ -307,10 +307,10 @@ Algorithm: Menu System 4. Process choice with appropriate action 5. Return to menu or exit based on choice 6. Handle invalid inputs gracefully -```cpp +``` **Input Validation Loop:** -```cpp +``` While input is invalid: Display prompt Get user input @@ -320,7 +320,7 @@ While input is invalid: Else: Display error message Continue loop -```cpp +``` --- @@ -390,7 +390,7 @@ While input is invalid: - [ ] Loop until user chooses exit **Menu Structure:** -```cpp +``` While user hasn't chosen exit: Display menu Get choice @@ -402,7 +402,7 @@ While user hasn't chosen exit: Exit program Else: Display invalid choice message -```cpp +``` --- @@ -549,7 +549,7 @@ Expected implementation provided. ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/.archive/stage-3-original-20251105/level-5/lesson.md b/lessons/c-c++/.archive/stage-3-original-20251105/level-5/lesson.md index 42302c0..424a834 100644 --- a/lessons/c-c++/.archive/stage-3-original-20251105/level-5/lesson.md +++ b/lessons/c-c++/.archive/stage-3-original-20251105/level-5/lesson.md @@ -88,7 +88,7 @@ Eligibility rules: - [ ] Employed applicants get preferred rates **Example:** -```cpp +``` === Loan Application === Enter credit score (300-850): 720 Enter annual income: 45000 @@ -100,7 +100,7 @@ ELIGIBLE! Loan amount: $100,000 Interest rate: 6.5% Monthly payment: $632.07 -```cpp +``` **Your Task:** 1. Write pseudocode for loan eligibility rules @@ -120,7 +120,7 @@ Create an insurance premium calculator with rules: - [ ] Coverage level: Basic (+0%), Standard (+25%), Premium (+50%) **Example:** -```cpp +``` === Insurance Quote === Enter age: 28 Enter accidents in last 3 years: 0 @@ -129,7 +129,7 @@ Enter coverage level (basic/standard/premium): standard Annual Premium: $687.50 (Base: $500 + Age: $0 + Record: -$50 + Vehicle: $0 + Coverage: $125) -```cpp +``` **Your Task:** 1. Write pseudocode for premium calculation rules @@ -155,7 +155,7 @@ Award levels: - [ ] Honorable mention: GPA >=3.5 AND essay >=7 **Example:** -```cpp +``` === Scholarship Application === Enter GPA (0.0-4.0): 3.8 Enter family income: 35000 @@ -166,7 +166,7 @@ Enter recommendation score (1-10): 9 AWARD: Partial Scholarship Reason: Strong GPA and leadership experience -```cpp +``` **Your Task:** 1. Write pseudocode for scholarship rules @@ -188,7 +188,7 @@ Create a tax calculator for 2024 tax brackets: Also calculate effective tax rate and after-tax income. **Example:** -```cpp +``` === Tax Calculator === Enter annual income: 75000 @@ -201,7 +201,7 @@ Tax breakdown: 10% bracket: $1,100.00 12% bracket: $4,032.00 22% bracket: $3,715.50 -```cpp +``` **Your Task:** 1. Write pseudocode for tax bracket calculations @@ -224,7 +224,7 @@ Create a simple medical diagnosis assistant with symptoms: Provide diagnosis and recommend seeing a doctor if multiple symptoms match. **Example:** -```cpp +``` === Symptom Checker === Do you have a fever? (y/n): y Do you have a cough? (y/n): y @@ -234,7 +234,7 @@ Do you feel nauseous? (y/n): n Possible diagnosis: Flu Recommendation: Rest, drink fluids, see doctor if symptoms worsen -```cpp +``` **Your Task:** 1. Write pseudocode for diagnosis rules @@ -260,7 +260,7 @@ Screening rules: - [ ] Offer: Interview qualified AND salary match AND local **Example:** -```cpp +``` === Application Screening === Enter years of experience: 4 Enter education level (HS/Associate/BS/MS): BS @@ -271,7 +271,7 @@ Offered salary range: 80000-90000 SCREENING RESULT: Interview Reason: Good experience, education, and skills match -```cpp +``` **Your Task:** 1. Write pseudocode for screening rules @@ -283,7 +283,7 @@ Reason: Good experience, education, and skills match ### Decision Logic Guidelines **Rule Engine Structure:** -```cpp +``` Algorithm: Decision Engine 1. Gather all input criteria 2. Evaluate primary rules first @@ -291,17 +291,17 @@ Algorithm: Decision Engine 4. Apply rule combinations (AND/OR) 5. Determine final decision 6. Provide reasoning for decision -```cpp +``` **Complex Condition Handling:** -```cpp +``` If (condition_A AND condition_B) OR (condition_C AND condition_D): Outcome 1 Else if condition_E OR (condition_F AND condition_G): Outcome 2 Else: Default outcome -```cpp +``` --- @@ -371,7 +371,7 @@ Else: - [ ] Calculation of loan terms if eligible **Decision Tree:** -```cpp +``` If (credit >= 650 AND income >= 30000 AND dti < 40) OR (credit >= 700 AND income >= 25000): If loan_amount <= income * 3: ELIGIBLE @@ -380,7 +380,7 @@ If (credit >= 650 AND income >= 30000 AND dti < 40) OR (credit >= 700 AND income INELIGIBLE - Loan too large Else: INELIGIBLE - Doesn't meet criteria -```cpp +``` --- @@ -392,14 +392,14 @@ Else: - [ ] Percentage-based modifications **Calculation Structure:** -```cpp +``` base_premium = 500 age_adjustment = calculate_age_factor(age) record_adjustment = calculate_record_factor(accidents) vehicle_adjustment = calculate_vehicle_factor(type) coverage_adjustment = calculate_coverage_factor(level) total = base + age + record + vehicle + coverage -```cpp +``` --- @@ -411,7 +411,7 @@ total = base + age + record + vehicle + coverage - [ ] Priority ranking for awards **Evaluation Logic:** -```cpp +``` score = 0 If GPA >= 3.5: score += 1 If income < 50000: score += 1 @@ -423,7 +423,7 @@ If recommendation >= 8: score += 1 If score >= 5 AND GPA == 4.0: Full Scholarship Else if score >= 4: Partial Scholarship Else if score >= 3: Honorable Mention -```cpp +``` --- @@ -435,7 +435,7 @@ Else if score >= 3: Honorable Mention - [ ] Marginal vs effective rates **Tax Calculation:** -```cpp +``` taxable = income - deduction tax = 0 @@ -449,7 +449,7 @@ If taxable > 0: bracket2 = min(taxable, 33725) tax += bracket2 * 0.12 // Continue for other brackets -```cpp +``` --- @@ -461,7 +461,7 @@ If taxable > 0: - [ ] Multiple possible diagnoses **Diagnosis Logic:** -```cpp +``` flu_score = 0 if fever: flu_score += 1 if cough or fatigue: flu_score += 1 @@ -473,7 +473,7 @@ if headache: cold_score += 1 if fatigue or nausea: cold_score += 1 // Compare scores and determine diagnosis -```cpp +``` --- @@ -485,7 +485,7 @@ if fatigue or nausea: cold_score += 1 - [ ] Multiple criteria evaluation **Screening Flow:** -```cpp +``` If experience < 2 AND education < BS AND skills < 2: REJECT Else if experience >= 3 OR education >= BS: @@ -498,7 +498,7 @@ Else if experience >= 3 OR education >= BS: PHONE_SCREEN Else: HOLD -```cpp +``` --- @@ -566,7 +566,7 @@ Expected implementation provided. ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/.archive/stage-3-original-20251105/level-6/lesson.md b/lessons/c-c++/.archive/stage-3-original-20251105/level-6/lesson.md index 7684cf2..d4a0f2f 100644 --- a/lessons/c-c++/.archive/stage-3-original-20251105/level-6/lesson.md +++ b/lessons/c-c++/.archive/stage-3-original-20251105/level-6/lesson.md @@ -85,7 +85,7 @@ Create a program that generates different star patterns based on user input: Ask for pattern type and size, then display the pattern. **Example:** -```cpp +``` Enter pattern type (1-4): 1 Enter size: 5 @@ -94,7 +94,7 @@ Enter size: 5 *** **** ***** -```cpp +``` **Your Task:** 1. Write pseudocode for pattern generation algorithms @@ -115,7 +115,7 @@ Create a program that generates number patterns: Display the pattern up to a user-specified limit. **Example:** -```cpp +``` Enter pattern type (1-4): 2 Enter size: 5 @@ -123,7 +123,7 @@ Enter size: 5 1 x 2 = 2 ... 5 x 5 = 25 -```cpp +``` **Your Task:** 1. Write pseudocode for number pattern algorithms @@ -142,7 +142,7 @@ Create a program that calculates statistics for a series of numbers: - [ ] Show final summary **Example:** -```cpp +``` Enter numbers (enter -1 to stop): Number 1: 10 Count: 1, Sum: 10, Avg: 10.0, Min: 10, Max: 10 @@ -158,7 +158,7 @@ Sum: 30 Average: 15.0 Minimum: 10 Maximum: 20 -```cpp +``` **Your Task:** 1. Write pseudocode for statistics calculation loop @@ -179,7 +179,7 @@ Simulate growth over multiple years, showing: - [ ] Total growth over time **Example:** -```cpp +``` Enter initial population: 1000 Enter annual growth rate (%): 5 Enter years to simulate: 10 @@ -190,7 +190,7 @@ Year 2: 1050 → 1102 (+52) Year 10: 1628 → 1709 (+81) Total growth: 709 people -```cpp +``` **Your Task:** 1. Write pseudocode for growth simulation loop @@ -210,14 +210,14 @@ Create a program that searches for a target value in an array: - [ ] Show search efficiency **Example:** -```cpp +``` Enter array size: 5 Enter 5 numbers: 10 20 30 40 50 Enter target to search: 30 Target 30 found at position 3 Comparisons made: 3 -```cpp +``` **Your Task:** 1. Write pseudocode for linear search algorithm @@ -238,7 +238,7 @@ Create a savings account simulator with monthly compounding: Show balance each month and final totals. **Example:** -```cpp +``` Enter initial deposit: 1000 Enter monthly deposit: 100 Enter annual interest rate (%): 6 @@ -251,7 +251,7 @@ Month 24: Balance $3,422.19 Total deposited: $3,400.00 Total interest earned: $422.19 -```cpp +``` **Your Task:** 1. Write pseudocode for savings simulation @@ -263,7 +263,7 @@ Total interest earned: $422.19 ### Loop Algorithm Guidelines **For Loop Structure:** -```cpp +``` Algorithm: Pattern Generator 1. Get size/input parameters 2. For i from 1 to size: @@ -271,10 +271,10 @@ Algorithm: Pattern Generator i. Print pattern element b. Move to next line 3. End pattern -```cpp +``` **While Loop Structure:** -```cpp +``` Algorithm: Data Processor 1. Initialize variables 2. While condition is true: @@ -282,7 +282,7 @@ Algorithm: Data Processor b. Update variables c. Check termination condition 3. Display final results -```cpp +``` --- @@ -353,22 +353,22 @@ Algorithm: Data Processor - [ ] Careful spacing and alignment **Right Triangle Pattern:** -```cpp +``` For i from 1 to size: For j from 1 to i: Print "*" Print newline -```cpp +``` **Pyramid Pattern:** -```cpp +``` For i from 1 to size: For spaces from 1 to (size-i): Print " " For stars from 1 to (2*i-1): Print "*" Print newline -```cpp +``` --- @@ -380,12 +380,12 @@ For i from 1 to size: - [ ] Variable increment patterns **Multiplication Table:** -```cpp +``` For i from 1 to size: For j from 1 to size: Print i + " x " + j + " = " + (i*j) Print newline -```cpp +``` --- @@ -397,7 +397,7 @@ For i from 1 to size: - [ ] Multiple statistics to track **Loop Structure:** -```cpp +``` Initialize: count=0, sum=0, min=MAX, max=MIN While true: Get number @@ -408,7 +408,7 @@ While true: if number > max: max = number Display current stats Display final summary -```cpp +``` --- @@ -420,14 +420,14 @@ Display final summary - [ ] Cumulative tracking **Growth Loop:** -```cpp +``` current_pop = initial For year from 1 to years: growth = current_pop * (rate/100) new_pop = current_pop + growth Display year, current_pop, new_pop, growth current_pop = new_pop -```cpp +``` --- @@ -439,7 +439,7 @@ For year from 1 to years: - [ ] Early termination on find **Search Algorithm:** -```cpp +``` found = false position = -1 comparisons = 0 @@ -453,7 +453,7 @@ If found: Display position and comparisons Else: Display not found -```cpp +``` --- @@ -465,7 +465,7 @@ Else: - [ ] Interest calculation per month **Monthly Simulation:** -```cpp +``` balance = initial_deposit total_deposited = initial_deposit monthly_rate = annual_rate / 100 / 12 @@ -480,7 +480,7 @@ For month from 1 to (years * 12): balance += interest Display month details -```cpp +``` --- @@ -548,7 +548,7 @@ Expected implementation provided. ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/.archive/stage-3-original-20251105/level-7/lesson.md b/lessons/c-c++/.archive/stage-3-original-20251105/level-7/lesson.md index ed68d18..4561d8e 100644 --- a/lessons/c-c++/.archive/stage-3-original-20251105/level-7/lesson.md +++ b/lessons/c-c++/.archive/stage-3-original-20251105/level-7/lesson.md @@ -84,7 +84,7 @@ Create a comprehensive student management system with: - [ ] Student search and modification **Example:** -```cpp +``` === Student Management System === 1. Register Student 2. Add Grades @@ -100,7 +100,7 @@ Enter number of courses: 3 Enter courses: Math Physics Chemistry Student registered successfully! -```cpp +``` **Your Task:** 1. Write pseudocode for the complete student management system @@ -121,7 +121,7 @@ Create an inventory system for a store with: - [ ] Product search and modification **Example:** -```cpp +``` === Inventory Management === 1. Add Product 2. Update Stock @@ -136,7 +136,7 @@ Enter quantity to sell: 2 Sale processed! Total: $29.98 Stock updated: Widget (8 remaining) -```cpp +``` **Your Task:** 1. Write pseudocode for inventory system integration @@ -158,7 +158,7 @@ Create a banking system with multiple account types: - [ ] Balance inquiries **Example:** -```cpp +``` === Banking System === 1. Create Account 2. Deposit @@ -176,7 +176,7 @@ Amount to transfer: 500 Transfer successful! Account 1001 balance: $1,500.00 Account 1002 balance: $2,500.00 -```cpp +``` **Your Task:** 1. Write pseudocode for banking system components @@ -198,7 +198,7 @@ Create a hospital management system with: - [ ] Patient search and reports **Example:** -```cpp +``` === Hospital Management === 1. Register Patient 2. Schedule Appointment @@ -215,7 +215,7 @@ Enter time: 14:00 Enter doctor: Dr. Smith Appointment scheduled successfully! -```cpp +``` **Your Task:** 1. Write pseudocode for hospital system workflow @@ -237,7 +237,7 @@ Create an online shopping system with: - [ ] Customer reviews and ratings **Example:** -```cpp +``` === E-commerce System === 1. Browse Products 2. Add to Cart @@ -252,7 +252,7 @@ Enter product ID: 2001 Enter quantity: 2 Added to cart! Cart total: $49.98 -```cpp +``` **Your Task:** 1. Write pseudocode for e-commerce system integration @@ -274,7 +274,7 @@ Create a game character management system with: - [ ] Character statistics display **Example:** -```cpp +``` === Character System === 1. Create Character 2. Manage Inventory @@ -291,7 +291,7 @@ Enter experience gained: 500 Quest completed! Experience: +500 Level up! Now level 5 New stats: HP +20, Attack +5 -```cpp +``` **Your Task:** 1. Write pseudocode for game character system @@ -303,7 +303,7 @@ New stats: HP +20, Attack +5 ### System Architecture Guidelines **Modular Design:** -```cpp +``` System: Complex Application ├── Component 1: Data Management │ ├── Function: Add Data @@ -321,15 +321,15 @@ System: Complex Application ├── Initialize System ├── Process User Requests └── Maintain System State -```cpp +``` **Data Flow Planning:** -```cpp +``` User Input → Validation → Processing → Storage → Output ↓ ↓ ↓ ↓ Error Handling Business Database Display Messages Logic Updates Results -```cpp +``` --- @@ -412,10 +412,10 @@ struct Student { int attendance[365]; // 1 year int course_count; }; -```cpp +``` **Main System Loop:** -```cpp +``` While running: Display menu Get choice @@ -425,7 +425,7 @@ While running: Case 3: Mark attendance Case 4: Generate student report Case 5: Search and display student -```cpp +``` --- @@ -455,14 +455,14 @@ While running: - [ ] Statement Generation (period reports) **Transaction Flow:** -```cpp +``` Validate accounts exist Check sufficient funds Update balances Record transaction in history Update interest calculations Generate confirmation -```cpp +``` --- @@ -476,11 +476,11 @@ Generate confirmation - [ ] Discharge Processing (final reports) **Patient Journey:** -```cpp +``` Registration → Appointment → Doctor Assignment → Treatment → Discharge ↓ ↓ ↓ ↓ ↓ Data Entry Scheduling Assignment Recording Processing -```cpp +``` --- @@ -494,11 +494,11 @@ Registration → Appointment → Doctor Assignment → Treatment → Discharge - [ ] Inventory Integration (stock updates) **Shopping Workflow:** -```cpp +``` Browse → Add to Cart → Checkout → Process Order → Update Inventory ↓ ↓ ↓ ↓ ↓ Catalog Cart Mgmt Payment Order Creation Stock Reduction -```cpp +``` --- @@ -512,11 +512,11 @@ Catalog Cart Mgmt Payment Order Creation Stock Reduction - [ ] Statistics Display (current status) **Character Development:** -```cpp +``` Creation → Questing → Leveling → Equipment → Stats Growth ↓ ↓ ↓ ↓ ↓ Setup Progress Rewards Upgrades Improvements -```cpp +``` --- @@ -590,7 +590,7 @@ Expected implementation provided. ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/.archive/stage-4-original-20251105/level-1/lesson.md b/lessons/c-c++/.archive/stage-4-original-20251105/level-1/lesson.md index 064de0c..12df061 100644 --- a/lessons/c-c++/.archive/stage-4-original-20251105/level-1/lesson.md +++ b/lessons/c-c++/.archive/stage-4-original-20251105/level-1/lesson.md @@ -81,7 +81,7 @@ typedef struct { int student_count; char filename[100]; } GradeBook; -```cpp +``` ### Function Modules - [ ] **File Operations**: `save_data()`, `load_data()` @@ -135,7 +135,7 @@ void display_menu(void); int get_user_choice(void); # endif -```cpp +``` ### Implementation File (gradebook.c) ```c @@ -331,7 +331,7 @@ int get_user_choice(void) { scanf("%d", &choice); return choice; } -```cpp +``` ### Main Program (main.c) ```c @@ -411,20 +411,20 @@ int main() { return 0; } -```cpp +``` --- ## Testing the Application ### Compilation Instructions -```bash +``` # Compile the program g++ -o gradebook main.c gradebook.c # Run the program ./gradebook -```cpp +``` ### Test Scenarios 1. **Add Students**: Try adding 2-3 students with different IDs @@ -434,7 +434,7 @@ g++ -o gradebook main.c gradebook.c 5. **Error Handling**: Test invalid IDs, out-of-range grades ### Sample Usage -```cpp +``` === Grade Management System === 1. Add Student 2. Add Grade @@ -461,7 +461,7 @@ Name: Alice Johnson Number of grades: 1 GPA: 95.50 Grades: 95.50 -```cpp +``` --- @@ -555,12 +555,12 @@ Grades: 95.50 5. **Cleanup**: Proper resource management ### Data Flow -```cpp +``` User Input → Validation → Processing → Storage → Display ↓ ↓ ↓ ↓ Error Messages Business File I/O UI Updates and Recovery Logic Operations Feedback -```cpp +``` --- @@ -632,7 +632,7 @@ Expected implementation provided. ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/.archive/stage-4-original-20251105/level-2/lesson.md b/lessons/c-c++/.archive/stage-4-original-20251105/level-2/lesson.md index 6e0d400..6147b31 100644 --- a/lessons/c-c++/.archive/stage-4-original-20251105/level-2/lesson.md +++ b/lessons/c-c++/.archive/stage-4-original-20251105/level-2/lesson.md @@ -93,7 +93,7 @@ typedef struct { char top_product[MAX_PRODUCT_NAME]; float top_product_revenue; } SalesStats; -```cpp +``` ### Function Modules - [ ] **File Operations**: `load_csv()`, `save_report()` @@ -163,7 +163,7 @@ int get_user_choice(void); void display_records(const SalesData *data, int limit); # endif -```cpp +``` ### Implementation File (sales_analyzer.c) ```c @@ -546,7 +546,7 @@ void analyze_by_product(const SalesData *data) { current_product, product_sales, product_revenue, avg_price); } } -```cpp +``` ### Main Program (main.c) ```c @@ -642,7 +642,7 @@ int main() { free_sales_data(&data); return 0; } -```cpp +``` --- @@ -659,16 +659,16 @@ Date,Product,Quantity,UnitPrice 2024-01-03,Monitor,1,299.99 2024-01-04,Laptop,3,999.99 2024-01-04,Mouse,4,25.50 -```cpp +``` ### Compilation Instructions -```bash +``` # Compile the program g++ -o sales_analyzer main.c sales_analyzer.c -lm # Run the program ./sales_analyzer -```cpp +``` ### Test Scenarios 1. **Load Data**: Import the sample CSV file @@ -763,20 +763,20 @@ g++ -o sales_analyzer main.c sales_analyzer.c -lm ## Code Walkthrough ### Data Processing Pipeline -```cpp +``` CSV File → Parse Records → Validate Data → Store in Memory ↓ ↓ ↓ ↓ Error Clean Data Validated In-Memory Handling Extraction Records Database -```cpp +``` ### Analysis Workflow -```cpp +``` Raw Data → Statistical Calculations → Grouping Operations → Report Generation ↓ ↓ ↓ ↓ Data Loading Summary Stats Date/Product Formatted Output Validation & Averages Analysis & File Export -```cpp +``` --- @@ -848,7 +848,7 @@ Expected implementation provided. ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/.archive/stage-4-original-20251105/level-3/lesson.md b/lessons/c-c++/.archive/stage-4-original-20251105/level-3/lesson.md index 9da0d42..92eafdf 100644 --- a/lessons/c-c++/.archive/stage-4-original-20251105/level-3/lesson.md +++ b/lessons/c-c++/.archive/stage-4-original-20251105/level-3/lesson.md @@ -89,7 +89,7 @@ typedef struct { double min; double max; } StatisticalData; -```cpp +``` ### Function Modules - [ ] **Calculator**: `scientific_calc()`, `basic_arithmetic()` @@ -188,7 +188,7 @@ int get_user_choice(void); void clear_input_buffer(void); # endif -```cpp +``` ### Implementation File (math_toolbox.c) ```c @@ -554,7 +554,7 @@ void clear_input_buffer(void) { int c; while ((c = getchar()) != '\n' && c != EOF); } -```cpp +``` ### Main Program (main.c) ```c @@ -845,20 +845,20 @@ int main() { return 0; } -```cpp +``` --- ## Testing the Application ### Compilation Instructions -```bash +``` # Compile the program g++ -o math_toolbox main.c math_toolbox.c -lm # Run the program ./math_toolbox -```cpp +``` ### Test Scenarios 1. **Scientific Calculator**: Test sin(30), log(100), sqrt(144) @@ -869,7 +869,7 @@ g++ -o math_toolbox main.c math_toolbox.c -lm 6. **Number Theory**: Check if 17 is prime, factorize 60 ### Sample Usage -```cpp +``` === Math Toolbox === 1. Scientific Calculator 2. Equation Solver @@ -891,7 +891,7 @@ Solve ax² + bx + c = 0 Enter a, b, c: 1 5 6 Equation: 1.00x² + 5.00x + 6.00 = 0 Roots: -2.0000, -3.0000 -```cpp +``` --- @@ -983,20 +983,20 @@ Roots: -2.0000, -3.0000 ## Code Walkthrough ### Mathematical Computation Flow -```cpp +``` User Input → Validation → Mathematical Calculation → Precision Check → Formatted Output ↓ ↓ ↓ ↓ ↓ Input Parsing Constraint Algorithm Execution Rounding/Precision Display Results and Cleaning Checking and Processing Error Handling with Units -```cpp +``` ### Algorithm Selection -```cpp +``` Problem Type → Algorithm Choice → Implementation → Testing → Optimization ↓ ↓ ↓ ↓ ↓ Mathematical Numerical Methods Code Writing Validation Performance Classification Selection & Debugging & Accuracy Tuning -```cpp +``` --- @@ -1068,7 +1068,7 @@ Expected implementation provided. ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/.archive/stage-4-original-20251105/level-4/lesson.md b/lessons/c-c++/.archive/stage-4-original-20251105/level-4/lesson.md index 01dbaf0..89c7d3a 100644 --- a/lessons/c-c++/.archive/stage-4-original-20251105/level-4/lesson.md +++ b/lessons/c-c++/.archive/stage-4-original-20251105/level-4/lesson.md @@ -130,7 +130,7 @@ typedef struct { int goal_count; char data_file[256]; } BudgetTracker; -```cpp +``` ### Function Modules - [ ] **User Interface**: `display_main_menu()`, `handle_navigation()` @@ -272,7 +272,7 @@ double get_positive_amount(const char *prompt); void display_help(void); # endif -```cpp +``` ### Implementation File (budget_tracker.c) ```c @@ -804,7 +804,7 @@ int load_data(BudgetTracker *tracker) { std::cout << " Data loaded successfully!\n"); return 1; } -```cpp +``` ### Main Program (main.c) ```c @@ -1077,20 +1077,20 @@ void display_budget_vs_actual(const BudgetTracker *tracker) { display_budget_status(tracker); } -```cpp +``` --- ## Testing the Application ### Compilation Instructions -```bash +``` # Compile the program g++ -o budget_tracker main.c budget_tracker.c # Run the program ./budget_tracker -```cpp +``` ### Test Scenarios 1. **Setup**: Add a checking account with $1000 balance @@ -1101,7 +1101,7 @@ g++ -o budget_tracker main.c budget_tracker.c 6. **Persistence**: Save and reload data ### Sample Usage Flow -```cpp +``` === Main Menu === 1. View Dashboard 2. Manage Accounts @@ -1122,7 +1122,7 @@ Account type: Enter type (1-4): 1 Enter starting balance: $1000 Account 'My Checking' added successfully! -```cpp +``` --- @@ -1214,20 +1214,20 @@ Enter starting balance: $1000 ## Code Walkthrough ### Application Flow -```cpp +``` Start → Load Data → Main Menu Loop → Feature Selection → Sub-Menu Navigation ↓ ↓ ↓ ↓ ↓ Initialize File I/O User Choice Process Request Context Menus Structures Operations Validation Execute Action User Input -```cpp +``` ### Data Management -```cpp +``` User Actions → Input Validation → Data Processing → Storage Update → UI Refresh ↓ ↓ ↓ ↓ ↓ Menu Selection Constraint Business Logic File I/O Display Update and Input Checking Calculations Operations Results -```cpp +``` --- @@ -1299,7 +1299,7 @@ Expected implementation provided. ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/.archive/stage-4-original-20251105/level-5/lesson.md b/lessons/c-c++/.archive/stage-4-original-20251105/level-5/lesson.md index 1068dcc..50c557f 100644 --- a/lessons/c-c++/.archive/stage-4-original-20251105/level-5/lesson.md +++ b/lessons/c-c++/.archive/stage-4-original-20251105/level-5/lesson.md @@ -117,7 +117,7 @@ typedef struct { double monthly_income; char analysis_period[20]; } SmartAnalyzer; -```cpp +``` ### Function Modules - [ ] **Data Analysis**: `analyze_spending_patterns()`, `detect_anomalies()` @@ -235,7 +235,7 @@ int compare_dates(const char *date1, const char *date2); void get_current_date(char *date); # endif -```cpp +``` ### Implementation File (smart_analyzer.c) ```c @@ -775,7 +775,7 @@ void get_current_date(char *date) { struct tm *tm_info = localtime(&t); strftime(date, 11, "%Y-%m-%d", tm_info); } -```cpp +``` ### Main Program (main.c) ```c @@ -861,20 +861,20 @@ int main() { return 0; } -```cpp +``` --- ## Testing the Application ### Compilation Instructions -```bash +``` # Compile the program g++ -o smart_analyzer main.c smart_analyzer.c -lm # Run the program ./smart_analyzer -```cpp +``` ### Test Scenarios 1. **Dashboard**: View overall financial health and forecasts @@ -885,7 +885,7 @@ g++ -o smart_analyzer main.c smart_analyzer.c -lm 6. **Report**: Generate comprehensive financial analysis ### Sample Analysis Output -```cpp +``` FINANCIAL DASHBOARD ════════════════════════ Monthly Income: $5000.00 @@ -898,7 +898,7 @@ Risk Level: Low FORECASTS Next Month Expenses: $1289.34 Savings Potential: $234.56 -```cpp +``` --- @@ -988,20 +988,20 @@ Savings Potential: $234.56 ## Code Walkthrough ### Intelligence Pipeline -```cpp +``` Data Collection → Pattern Recognition → Analysis & Scoring → Recommendation Generation → User Presentation ↓ ↓ ↓ ↓ ↓ Expense Loading Trend Detection Financial Health Personalized Advice Interactive Display & Validation & Anomaly Finding Assessment & Risk Priority Ranking & Guidance -```cpp +``` ### Decision Support Flow -```cpp +``` User Goals → Spending Analysis → Risk Assessment → Recommendation Filtering → Actionable Advice ↓ ↓ ↓ ↓ ↓ Goal Input Pattern Recognition Vulnerability Personalization Implementation Collection & Trend Analysis Analysis & Scoring & Prioritization Guidance -```cpp +``` --- @@ -1073,7 +1073,7 @@ Expected implementation provided. ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/.archive/stage-4-original-20251105/level-6/lesson.md b/lessons/c-c++/.archive/stage-4-original-20251105/level-6/lesson.md index bae3ff1..83328ed 100644 --- a/lessons/c-c++/.archive/stage-4-original-20251105/level-6/lesson.md +++ b/lessons/c-c++/.archive/stage-4-original-20251105/level-6/lesson.md @@ -141,7 +141,7 @@ typedef struct { char log_file[256]; int automation_enabled; } AutomationSuite; -```cpp +``` ### Function Modules - [ ] **Task Scheduler**: `schedule_task()`, `execute_pending_tasks()` @@ -302,7 +302,7 @@ long long get_file_size(const char *filename); int copy_file(const char *source, const char *dest); # endif -```cpp +``` ### Implementation File (automation_suite.c) ```c @@ -842,7 +842,7 @@ int copy_file(const char *source, const char *dest) { fclose(dst); return 1; } -```cpp +``` ### Main Program (main.c) ```c @@ -1030,20 +1030,20 @@ void generate_backup_report(const AutomationSuite *suite) { fclose(report); std::cout << " Backup report generated: backup_report.txt\n"); } -```cpp +``` --- ## Testing the Application ### Compilation Instructions -```bash +``` # Compile the program g++ -o productivity_suite main.c automation_suite.c # Run the program ./productivity_suite -```cpp +``` ### Test Scenarios 1. **Task Manager**: View scheduled tasks and their status @@ -1054,7 +1054,7 @@ g++ -o productivity_suite main.c automation_suite.c 6. **System Health**: Check overall system status ### Sample Automation Flow -```cpp +``` === Main Menu === 1. Task Manager ... @@ -1065,7 +1065,7 @@ Enter your choice (1-8): 6 Generating Productivity Report... Productivity report generated: productivity_report.txt Automation cycle completed -```cpp +``` --- @@ -1161,20 +1161,20 @@ Enter your choice (1-8): 6 ## Code Walkthrough ### Automation Engine Flow -```cpp +``` Initialization → Schedule Loading → Main Loop → Time Check → Task Execution ↓ ↓ ↓ ↓ ↓ System Setup Task Queue User Input Due Tasks Function Call Configuration Management Processing Selection & Monitoring -```cpp +``` ### Scheduling Algorithm -```cpp +``` Task Queue → Time Comparison → Priority Sorting → Resource Check → Execution ↓ ↓ ↓ ↓ ↓ Pending Tasks Schedule Match High Priority Available Run Task Identification Comparison Task Selection Resources & Update -```cpp +``` --- @@ -1246,7 +1246,7 @@ Expected implementation provided. ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/.archive/stage-4-original-20251105/level-7/lesson.md b/lessons/c-c++/.archive/stage-4-original-20251105/level-7/lesson.md index 36dd2c5..49adfdf 100644 --- a/lessons/c-c++/.archive/stage-4-original-20251105/level-7/lesson.md +++ b/lessons/c-c++/.archive/stage-4-original-20251105/level-7/lesson.md @@ -101,7 +101,7 @@ typedef struct { AlertSystem *alerts; ImportExport *data_handler; } FinanceApplication; -```cpp +``` ### Key Data Structures ```c @@ -195,7 +195,7 @@ typedef struct { double alert_price_high; double alert_price_low; } Investment; -```cpp +``` ### Advanced Features Structure ```c @@ -232,7 +232,7 @@ typedef struct { RecurringTransaction recurring[100]; int recurring_count; } AutomationRules; -```cpp +``` --- @@ -385,7 +385,7 @@ int validate_date(const char *date); void format_currency(char *buffer, double amount); # endif -```cpp +``` ### Core Implementation File (finance_manager.c) ```c @@ -1053,7 +1053,7 @@ void format_currency(char *buffer, double amount) { sprintf(buffer, "$%.2f", amount); } } -```cpp +``` ### Main Program (main.c) ```c @@ -1335,20 +1335,20 @@ int main() { return 0; } -```cpp +``` --- ## Testing the Application ### Compilation Instructions -```bash +``` # Compile the program g++ -o finance_manager main.c finance_manager.c # Run the program ./finance_manager -```cpp +``` ### Test Scenarios 1. **Setup**: Add checking and savings accounts @@ -1360,7 +1360,7 @@ g++ -o finance_manager main.c finance_manager.c 7. **Data**: Save and reload financial data ### Sample Usage Flow -```cpp +``` === Main Menu === 1. Dashboard ... @@ -1374,7 +1374,7 @@ Enter account name: My Checking Account type (1-Checking, 2-Savings, 3-Credit Card, 4-Investment, 5-Loan, 6-Retirement): 1 Enter institution: Bank of America Account 'My Checking' added successfully! -```cpp +``` --- @@ -1492,21 +1492,21 @@ Enter institution: Bank of America ## Code Walkthrough ### System Architecture Flow -```cpp +``` User Interface Layer → Business Logic Layer → Data Access Layer → Persistence Layer ↓ ↓ ↓ ↓ Menu Navigation Financial Data Structures File I/O & Input Handling Calculations & Memory Management & Backup -```cpp +``` ### Financial Processing Pipeline -```cpp +``` Transaction Input → Validation → Categorization → Account Update → Budget Check → Goal Update → Analytics Update ↓ ↓ ↓ ↓ ↓ ↓ ↓ Data Entry Rule Validation Smart Tagging Balance Calc Variance Progress Trend Analysis & Capture & Constraint & Learning & Synchronization Analysis Tracking & Forecasting Checking Enforcement Algorithms & Persistence & Alerts -```cpp +``` --- @@ -1586,7 +1586,7 @@ Expected implementation provided. ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/.archive/stage-5-original-20251105/level-1/lesson.md b/lessons/c-c++/.archive/stage-5-original-20251105/level-1/lesson.md index 555465c..31ba23c 100644 --- a/lessons/c-c++/.archive/stage-5-original-20251105/level-1/lesson.md +++ b/lessons/c-c++/.archive/stage-5-original-20251105/level-1/lesson.md @@ -189,7 +189,7 @@ Your capstone will be evaluated on: Before coding, submit a proposal addressing: -```cpp +``` PROJECT TITLE: [Name] DOMAIN: [Category - e.g., Personal Finance, Education] PURPOSE: [What problem does it solve?] @@ -217,7 +217,7 @@ USER INTERFACE: - [What menus or prompts?] ESTIMATED EFFORT: [X hours of work] -```cpp +``` --- @@ -387,15 +387,15 @@ From **Stage 4**: File I/O, data structures, system design **Essential Planning Steps:** 1. **Write a Problem Statement** - ```cpp + ``` "My application solves [problem] by [approach] for [users] so that [outcome]." - ```cpp + ``` 2. **Define Core Features** (3-5 minimum) - ```cpp + ``` MUST HAVE (critical): - Feature A - Feature B @@ -406,7 +406,7 @@ From **Stage 4**: File I/O, data structures, system design NICE TO HAVE (bonus): - Feature E - ```cpp + ``` 3. **Design Data Structures** ```c @@ -421,10 +421,10 @@ From **Stage 4**: File I/O, data structures, system design int employee_count; // ... other fields }; - ```cpp + ``` 4. **Create Architecture Diagram** - ```cpp + ``` USER INPUT ↓ MENU SYSTEM @@ -434,10 +434,10 @@ From **Stage 4**: File I/O, data structures, system design DATA STORAGE (structs) ↓ FILE I/O (persistence) - ```cpp + ``` 5. **Write Pseudocode for Main Functions** - ```cpp + ``` Algorithm: AddNewRecord 1. Get input from user 2. Validate input @@ -452,7 +452,7 @@ From **Stage 4**: File I/O, data structures, system design 3. Check if record matches criteria 4. Display matching records 5. Ask if user wants to filter further - ```cpp + ``` ### Phase 3: Data Structure Design @@ -499,7 +499,7 @@ void add_entity(EntityManager *manager); void view_entities(EntityManager *manager); void search_entities(EntityManager *manager); void delete_entity(EntityManager *manager); -```cpp +``` ### Phase 4: Implementation Strategy @@ -522,7 +522,7 @@ void delete_entity(EntityManager *manager); **Create a Test Plan:** -```cpp +``` TEST CASE 1: Add New Record Input: Valid record data Expected: Record added, saved to file @@ -539,7 +539,7 @@ Expected: "No records found" message Result: PASS / FAIL ... (20-30 test cases minimum) -```cpp +``` ### Phase 6: Code Quality Checklist @@ -571,9 +571,9 @@ Result: PASS / FAIL - Note which are core vs. bonus 3. **Compilation Instructions** - ```bash + ``` g++ -o myapp main.c -lm - ```cpp + ``` 4. **Usage Guide** - How to run the program @@ -647,7 +647,7 @@ Result: PASS / FAIL ## Real-World Capstone Examples ### Example 1: Personal Finance Manager -```cpp +``` PURPOSE: Help track personal spending and savings goals FEATURES: - Add/categorize expenses @@ -655,10 +655,10 @@ FEATURES: - Generate spending reports - Export to CSV for analysis COMPLEXITY: Moderate (5-7 hours) -```cpp +``` ### Example 2: Quiz Application -```cpp +``` PURPOSE: Interactive quiz system for learning FEATURES: - Load questions from file @@ -666,10 +666,10 @@ FEATURES: - Provide instant feedback - Show statistics and progress COMPLEXITY: Moderate (6-8 hours) -```cpp +``` ### Example 3: Data Processor -```cpp +``` PURPOSE: Analyze CSV files and generate reports FEATURES: - Parse CSV files @@ -678,7 +678,7 @@ FEATURES: - Generate reports - Export results COMPLEXITY: Moderate to Advanced (8-12 hours) -```cpp +``` --- @@ -735,7 +735,7 @@ Expected implementation provided. ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/.archive/stage-5-original-20251105/level-2/lesson.md b/lessons/c-c++/.archive/stage-5-original-20251105/level-2/lesson.md index 5d005ac..9d6a8c3 100644 --- a/lessons/c-c++/.archive/stage-5-original-20251105/level-2/lesson.md +++ b/lessons/c-c++/.archive/stage-5-original-20251105/level-2/lesson.md @@ -188,7 +188,7 @@ Key functions and their purpose: ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/.archive/stage-5-original-20251105/level-3/lesson.md b/lessons/c-c++/.archive/stage-5-original-20251105/level-3/lesson.md index 5fbc47c..b399c47 100644 --- a/lessons/c-c++/.archive/stage-5-original-20251105/level-3/lesson.md +++ b/lessons/c-c++/.archive/stage-5-original-20251105/level-3/lesson.md @@ -165,7 +165,7 @@ Key functions and their purpose: ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/.archive/stage-5-original-20251105/level-4/lesson.md b/lessons/c-c++/.archive/stage-5-original-20251105/level-4/lesson.md index 6bcc8e9..111ea9d 100644 --- a/lessons/c-c++/.archive/stage-5-original-20251105/level-4/lesson.md +++ b/lessons/c-c++/.archive/stage-5-original-20251105/level-4/lesson.md @@ -110,7 +110,7 @@ Key functions and their purpose: ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/.archive/stage-5-original-20251105/level-5/lesson.md b/lessons/c-c++/.archive/stage-5-original-20251105/level-5/lesson.md index ee1426e..be4548c 100644 --- a/lessons/c-c++/.archive/stage-5-original-20251105/level-5/lesson.md +++ b/lessons/c-c++/.archive/stage-5-original-20251105/level-5/lesson.md @@ -100,7 +100,7 @@ Key functions and their purpose: ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/.archive/stage-5-original-20251105/level-6/lesson.md b/lessons/c-c++/.archive/stage-5-original-20251105/level-6/lesson.md index 5ac749b..68e312e 100644 --- a/lessons/c-c++/.archive/stage-5-original-20251105/level-6/lesson.md +++ b/lessons/c-c++/.archive/stage-5-original-20251105/level-6/lesson.md @@ -112,7 +112,7 @@ Key functions and their purpose: ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/.archive/stage-5-original-20251105/level-7/lesson.md b/lessons/c-c++/.archive/stage-5-original-20251105/level-7/lesson.md index f6e34ff..8d8bbf6 100644 --- a/lessons/c-c++/.archive/stage-5-original-20251105/level-7/lesson.md +++ b/lessons/c-c++/.archive/stage-5-original-20251105/level-7/lesson.md @@ -216,7 +216,7 @@ Key functions and their purpose: ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/stage-1/level-1/lesson.md b/lessons/c-c++/stage-1/level-1/lesson.md index e062416..e7092ab 100644 --- a/lessons/c-c++/stage-1/level-1/lesson.md +++ b/lessons/c-c++/stage-1/level-1/lesson.md @@ -28,7 +28,7 @@ int main() { ### How to Compile and Run -```bash +``` gcc main.c -o main ./main ``` @@ -68,3 +68,36 @@ Hello, World! --- **Next: Variables and data types!** + +--- + +## ANSWER KEY (No cheating until you've tried!) + +### Solution + +```c +#include + +int main() { + printf("Hello, World!\n"); + return 0; +} +``` + +### Explanation + +This solution demonstrates the key concepts from this lesson: + +1. **Basic Structure**: The program follows the standard structure for c +2. **Output**: The code produces the expected output +3. **Syntax**: Pay attention to the syntax details - they're important! + +### Success Criteria + +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does + +--- + +**Great job! You've completed this lesson!** diff --git a/lessons/c-c++/stage-1/level-2/lesson.md b/lessons/c-c++/stage-1/level-2/lesson.md index 50be1d8..32091e7 100644 --- a/lessons/c-c++/stage-1/level-2/lesson.md +++ b/lessons/c-c++/stage-1/level-2/lesson.md @@ -24,32 +24,32 @@ int main() { // Integer variables int age = 25; int year = 2025; - + // Floating point float height = 5.9; float price = 19.99; - + // Character char grade = 'A'; - + // Print them all printf("Age: %d\n", age); printf("Year: %d\n", year); printf("Height: %.1f feet\n", height); printf("Price: $%.2f\n", price); printf("Grade: %c\n", grade); - + // Basic arithmetic int sum = age + 5; printf("In 5 years you'll be: %d\n", sum); - + return 0; } ``` ### Compile and Run -```bash +``` gcc main.c -o main ./main ``` @@ -85,3 +85,57 @@ gcc main.c -o main --- **Next: User input with scanf()!** + +--- + +## ANSWER KEY (No cheating until you've tried!) + +### Solution + +```c +#include + +int main() { + // Integer variables + int age = 25; + int year = 2025; + + // Floating point + float height = 5.9; + float price = 19.99; + + // Character + char grade = 'A'; + + // Print them all + printf("Age: %d\n", age); + printf("Year: %d\n", year); + printf("Height: %.1f feet\n", height); + printf("Price: $%.2f\n", price); + printf("Grade: %c\n", grade); + + // Basic arithmetic + int sum = age + 5; + printf("In 5 years you'll be: %d\n", sum); + + return 0; +} +``` + +### Explanation + +This solution demonstrates the key concepts from this lesson: + +1. **Basic Structure**: The program follows the standard structure for c +2. **Output**: The code produces the expected output +3. **Syntax**: Pay attention to the syntax details - they're important! + +### Success Criteria + +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does + +--- + +**Great job! You've completed this lesson!** diff --git a/lessons/c-c++/stage-1/level-3/lesson.md b/lessons/c-c++/stage-1/level-3/lesson.md index 9b46619..118ebdd 100644 --- a/lessons/c-c++/stage-1/level-3/lesson.md +++ b/lessons/c-c++/stage-1/level-3/lesson.md @@ -24,34 +24,34 @@ int main() { int age; float height; char initial; - + // Get user input printf("Enter your age: "); scanf("%d", &age); - + printf("Enter your height in feet: "); scanf("%f", &height); - + printf("Enter your first initial: "); scanf(" %c", &initial); // Note the space before %c - + // Display results printf("\n--- Your Info ---\n"); printf("Initial: %c\n", initial); printf("Age: %d years old\n", age); printf("Height: %.1f feet\n", height); - + // Calculate something int months = age * 12; printf("That's %d months!\n", months); - + return 0; } ``` ### Compile and Run -```bash +``` gcc main.c -o main ./main ``` @@ -99,3 +99,59 @@ scanf("%d", &age); --- **Next: Conditional logic with if statements!** + +--- + +## ANSWER KEY (No cheating until you've tried!) + +### Solution + +```c +#include + +int main() { + int age; + float height; + char initial; + + // Get user input + printf("Enter your age: "); + scanf("%d", &age); + + printf("Enter your height in feet: "); + scanf("%f", &height); + + printf("Enter your first initial: "); + scanf(" %c", &initial); // Note the space before %c + + // Display results + printf("\n--- Your Info ---\n"); + printf("Initial: %c\n", initial); + printf("Age: %d years old\n", age); + printf("Height: %.1f feet\n", height); + + // Calculate something + int months = age * 12; + printf("That's %d months!\n", months); + + return 0; +} +``` + +### Explanation + +This solution demonstrates the key concepts from this lesson: + +1. **Basic Structure**: The program follows the standard structure for c +2. **Output**: The code produces the expected output +3. **Syntax**: Pay attention to the syntax details - they're important! + +### Success Criteria + +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does + +--- + +**Great job! You've completed this lesson!** diff --git a/lessons/c-c++/stage-1/level-4/lesson.md b/lessons/c-c++/stage-1/level-4/lesson.md index 5fb284a..9ca84d2 100644 --- a/lessons/c-c++/stage-1/level-4/lesson.md +++ b/lessons/c-c++/stage-1/level-4/lesson.md @@ -24,17 +24,17 @@ int main() { int age; float temperature; char hasUmbrella; - + // Get input printf("Enter your age: "); scanf("%d", &age); - + printf("Enter temperature (F): "); scanf("%f", &temperature); - + printf("Do you have an umbrella? (y/n): "); scanf(" %c", &hasUmbrella); - + // Age-based message printf("\n--- Analysis ---\n"); if (age < 13) { @@ -46,7 +46,7 @@ int main() { } else { printf("You're a senior!\n"); } - + // Weather advice if (temperature > 85) { printf("It's hot! Stay hydrated.\n"); @@ -55,24 +55,24 @@ int main() { } else { printf("Weather is nice!\n"); } - + // Multiple conditions if (temperature < 50 && hasUmbrella == 'n') { printf("Warning: Cold and no umbrella!\n"); } - + // Logical NOT if (!(age >= 18)) { printf("You're not an adult yet.\n"); } - + return 0; } ``` ### Compile and Run -```bash +``` gcc main.c -o main ./main ``` @@ -117,3 +117,80 @@ gcc main.c -o main --- **Next: Transitioning from C to C++!** + +--- + +## ANSWER KEY (No cheating until you've tried!) + +### Solution + +```c +#include + +int main() { + int age; + float temperature; + char hasUmbrella; + + // Get input + printf("Enter your age: "); + scanf("%d", &age); + + printf("Enter temperature (F): "); + scanf("%f", &temperature); + + printf("Do you have an umbrella? (y/n): "); + scanf(" %c", &hasUmbrella); + + // Age-based message + printf("\n--- Analysis ---\n"); + if (age < 13) { + printf("You're a kid!\n"); + } else if (age < 20) { + printf("You're a teenager!\n"); + } else if (age < 65) { + printf("You're an adult!\n"); + } else { + printf("You're a senior!\n"); + } + + // Weather advice + if (temperature > 85) { + printf("It's hot! Stay hydrated.\n"); + } else if (temperature < 32) { + printf("It's freezing! Bundle up!\n"); + } else { + printf("Weather is nice!\n"); + } + + // Multiple conditions + if (temperature < 50 && hasUmbrella == 'n') { + printf("Warning: Cold and no umbrella!\n"); + } + + // Logical NOT + if (!(age >= 18)) { + printf("You're not an adult yet.\n"); + } + + return 0; +} +``` + +### Explanation + +This solution demonstrates the key concepts from this lesson: + +1. **Basic Structure**: The program follows the standard structure for c +2. **Output**: The code produces the expected output +3. **Syntax**: Pay attention to the syntax details - they're important! + +### Success Criteria + +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does + +--- + +**Great job! You've completed this lesson!** diff --git a/lessons/c-c++/stage-1/level-5/lesson.md b/lessons/c-c++/stage-1/level-5/lesson.md index e396581..188dbad 100644 --- a/lessons/c-c++/stage-1/level-5/lesson.md +++ b/lessons/c-c++/stage-1/level-5/lesson.md @@ -17,7 +17,7 @@ Create `main.cpp` (note: `.cpp` not `.c`): -```cpp +``` #include using namespace std; @@ -26,37 +26,37 @@ int main() { int age; float height; string name; // New! C++ has built-in strings - + // C++ style output (no printf!) cout << "Enter your name: "; cin >> name; - + cout << "Enter your age: "; cin >> age; - + cout << "Enter your height (feet): "; cin >> height; - + // Output with cout (replaces printf) cout << "\n--- Your Info ---\n"; cout << "Name: " << name << "\n"; cout << "Age: " << age << " years\n"; cout << "Height: " << height << " feet\n"; - + // Conditionals work the same! if (age >= 18) { cout << "You're an adult!\n"; } else { cout << "You're a minor.\n"; } - + return 0; } ``` ### Compile and Run (note g++ not gcc!) -```bash +``` g++ main.cpp -o main ./main ``` @@ -78,7 +78,7 @@ g++ main.cpp -o main ### Understanding cout and cin -```cpp +``` cout << "Hello"; // Output - arrows point LEFT (out of program) cin >> age; // Input - arrows point RIGHT (into variable) ``` @@ -116,3 +116,64 @@ Think of the arrows as direction of data flow! --- **Next: Loops in C++!** + +--- + +## ANSWER KEY (No cheating until you've tried!) + +### Solution + +``` +#include +using namespace std; + +int main() { + // C++ style variables (same as C) + int age; + float height; + string name; // New! C++ has built-in strings + + // C++ style output (no printf!) + cout << "Enter your name: "; + cin >> name; + + cout << "Enter your age: "; + cin >> age; + + cout << "Enter your height (feet): "; + cin >> height; + + // Output with cout (replaces printf) + cout << "\n--- Your Info ---\n"; + cout << "Name: " << name << "\n"; + cout << "Age: " << age << " years\n"; + cout << "Height: " << height << " feet\n"; + + // Conditionals work the same! + if (age >= 18) { + cout << "You're an adult!\n"; + } else { + cout << "You're a minor.\n"; + } + + return 0; +} +``` + +### Explanation + +This solution demonstrates the key concepts from this lesson: + +1. **Basic Structure**: The program follows the standard structure for this language +2. **Output**: The code produces the expected output +3. **Syntax**: Pay attention to the syntax details - they're important! + +### Success Criteria + +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does + +--- + +**Great job! You've completed this lesson!** diff --git a/lessons/c-c++/stage-1/level-6/lesson.md b/lessons/c-c++/stage-1/level-6/lesson.md index 179141d..002a176 100644 --- a/lessons/c-c++/stage-1/level-6/lesson.md +++ b/lessons/c-c++/stage-1/level-6/lesson.md @@ -17,7 +17,7 @@ Create `main.cpp`: -```cpp +``` #include using namespace std; @@ -27,7 +27,7 @@ int main() { for (int i = 1; i <= 5; i++) { cout << "Count: " << i << "\n"; } - + // WHILE LOOP - keep asking until valid input cout << "\nWhile loop example:\n"; int number = 0; @@ -39,7 +39,7 @@ int main() { } } cout << "You entered: " << number << "\n"; - + // DO-WHILE - runs at least once cout << "\nDo-while loop:\n"; char again; @@ -48,7 +48,7 @@ int main() { cout << "Run again? (y/n): "; cin >> again; } while (again == 'y' || again == 'Y'); - + // BREAK and CONTINUE cout << "\nLoop control:\n"; for (int i = 1; i <= 10; i++) { @@ -61,14 +61,14 @@ int main() { cout << i << " "; } cout << "\n"; - + return 0; } ``` ### Compile and Run -```bash +``` g++ main.cpp -o main ./main ``` @@ -78,21 +78,21 @@ g++ main.cpp -o main ### Loop Types **FOR** - When you know how many iterations: -```cpp +``` for (initialization; condition; increment) { // code } ``` **WHILE** - When condition is checked first: -```cpp +``` while (condition) { // code } ``` **DO-WHILE** - When code must run at least once: -```cpp +``` do { // code } while (condition); @@ -127,3 +127,76 @@ do { --- **Next: Functions and introduction to classes!** + +--- + +## ANSWER KEY (No cheating until you've tried!) + +### Solution + +``` +#include +using namespace std; + +int main() { + // FOR LOOP - count from 1 to 5 + cout << "For loop:\n"; + for (int i = 1; i <= 5; i++) { + cout << "Count: " << i << "\n"; + } + + // WHILE LOOP - keep asking until valid input + cout << "\nWhile loop example:\n"; + int number = 0; + while (number < 1 || number > 10) { + cout << "Enter a number between 1-10: "; + cin >> number; + if (number < 1 || number > 10) { + cout << "Invalid! Try again.\n"; + } + } + cout << "You entered: " << number << "\n"; + + // DO-WHILE - runs at least once + cout << "\nDo-while loop:\n"; + char again; + do { + cout << "Hello from do-while!\n"; + cout << "Run again? (y/n): "; + cin >> again; + } while (again == 'y' || again == 'Y'); + + // BREAK and CONTINUE + cout << "\nLoop control:\n"; + for (int i = 1; i <= 10; i++) { + if (i == 5) { + continue; // Skip 5 + } + if (i == 8) { + break; // Stop at 8 + } + cout << i << " "; + } + cout << "\n"; + + return 0; +} +``` + +### Explanation + +This solution demonstrates the key concepts from this lesson: + +1. **Basic Structure**: The program follows the standard structure for this language +2. **Output**: The code produces the expected output +3. **Syntax**: Pay attention to the syntax details - they're important! + +### Success Criteria + +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does + +--- + +**Great job! You've completed this lesson!** diff --git a/lessons/c-c++/stage-1/level-7/lesson.md b/lessons/c-c++/stage-1/level-7/lesson.md index 635ef85..3cf7626 100644 --- a/lessons/c-c++/stage-1/level-7/lesson.md +++ b/lessons/c-c++/stage-1/level-7/lesson.md @@ -17,7 +17,7 @@ Create `main.cpp`: -```cpp +``` #include using namespace std; @@ -32,7 +32,7 @@ public: int multiply(int a, int b) { return a * b; } - + float divide(float a, float b) { if (b != 0) { return a / b; @@ -44,31 +44,31 @@ public: int main() { // Using functions cout << "=== Functions Demo ===\n"; - + string name; cout << "Enter your name: "; cin >> name; printWelcome(name); - + int x = 10, y = 5; int sum = add(x, y); cout << x << " + " << y << " = " << sum << "\n"; - + float weight, height; cout << "\nEnter weight (kg): "; cin >> weight; cout << "Enter height (m): "; cin >> height; - + float bmi = calculateBMI(weight, height); cout << "Your BMI: " << bmi << "\n"; - + // Using a class (preview!) cout << "\n=== Class Demo ===\n"; Calculator calc; cout << "15 * 3 = " << calc.multiply(15, 3) << "\n"; cout << "20 / 4 = " << calc.divide(20, 4) << "\n"; - + return 0; } @@ -88,7 +88,7 @@ float calculateBMI(float weight, float height) { ### Compile and Run -```bash +``` g++ main.cpp -o main ./main ``` @@ -97,7 +97,7 @@ g++ main.cpp -o main ### Function Structure -```cpp +``` returnType functionName(parameters) { // code return value; @@ -112,7 +112,7 @@ returnType functionName(parameters) { ### Classes - A Preview -```cpp +``` class ClassName { public: // Functions (called "methods") @@ -170,3 +170,96 @@ You've completed Stage 1! You now know: --- **Congratulations on finishing Stage 1! 🎉** + +--- + +## ANSWER KEY (No cheating until you've tried!) + +### Solution + +``` +#include +using namespace std; + +// Function declarations +int add(int a, int b); +float calculateBMI(float weight, float height); +void printWelcome(string name); + +// Simple class preview +class Calculator { +public: + int multiply(int a, int b) { + return a * b; + } + + float divide(float a, float b) { + if (b != 0) { + return a / b; + } + return 0; + } +}; + +int main() { + // Using functions + cout << "=== Functions Demo ===\n"; + + string name; + cout << "Enter your name: "; + cin >> name; + printWelcome(name); + + int x = 10, y = 5; + int sum = add(x, y); + cout << x << " + " << y << " = " << sum << "\n"; + + float weight, height; + cout << "\nEnter weight (kg): "; + cin >> weight; + cout << "Enter height (m): "; + cin >> height; + + float bmi = calculateBMI(weight, height); + cout << "Your BMI: " << bmi << "\n"; + + // Using a class (preview!) + cout << "\n=== Class Demo ===\n"; + Calculator calc; + cout << "15 * 3 = " << calc.multiply(15, 3) << "\n"; + cout << "20 / 4 = " << calc.divide(20, 4) << "\n"; + + return 0; +} + +// Function definitions +void printWelcome(string name) { + cout << "\nWelcome, " << name << "!\n"; +} + +int add(int a, int b) { + return a + b; +} + +float calculateBMI(float weight, float height) { + return weight / (height * height); +} +``` + +### Explanation + +This solution demonstrates the key concepts from this lesson: + +1. **Basic Structure**: The program follows the standard structure for this language +2. **Output**: The code produces the expected output +3. **Syntax**: Pay attention to the syntax details - they're important! + +### Success Criteria + +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does + +--- + +**Great job! You've completed this lesson!** diff --git a/lessons/c-c++/stage-2/level-1/lesson.md b/lessons/c-c++/stage-2/level-1/lesson.md index 56f0e2d..165cc83 100644 --- a/lessons/c-c++/stage-2/level-1/lesson.md +++ b/lessons/c-c++/stage-2/level-1/lesson.md @@ -26,7 +26,7 @@ Welcome to Stage 2! You've mastered copying code - now it's time to think like **Pseudocode** is a way to write programming logic in plain English (or your native language) before writing actual code. It's like writing a recipe or instructions for a task. **Example:** -```bash +``` Algorithm: Make a sandwich 1. Get bread from pantry 2. Get peanut butter from fridge @@ -35,7 +35,7 @@ Algorithm: Make a sandwich 5. Spread jelly on the other bread slice 6. Put slices together 7. Enjoy your sandwich! -```bash +``` This is much easier to understand than trying to write code first! @@ -50,13 +50,13 @@ This is much easier to understand than trying to write code first! ## Algorithm 1: Greeting Program **Pseudocode:** -```bash +``` Algorithm: Display Personal Greeting 1. Display "Hello! What's your name?" to the user 2. Get the user's name from input 3. Display "Nice to meet you, " followed by the user's name 4. Display "Welcome to programming!" -```bash +``` **Your Task:** Create a C program that follows these exact steps. @@ -65,7 +65,7 @@ Algorithm: Display Personal Greeting ## Algorithm 2: Simple Calculator **Pseudocode:** -```bash +``` Algorithm: Add Two Numbers 1. Ask user for first number 2. Get first number from user @@ -73,7 +73,7 @@ Algorithm: Add Two Numbers 4. Get second number from user 5. Calculate sum of the two numbers 6. Display "The sum is: " followed by the sum -```bash +``` **Your Task:** Create a C program that implements this calculator. @@ -82,14 +82,14 @@ Algorithm: Add Two Numbers ## Algorithm 3: Age Calculator **Pseudocode:** -```bash +``` Algorithm: Calculate Age in Days 1. Display "Enter your age in years: " 2. Get age in years from user 3. Calculate days = age × 365 4. Display "You are approximately " + days + " days old" 5. Display "That's a lot of days! " -```bash +``` **Your Task:** Create a program that calculates approximate age in days. @@ -98,7 +98,7 @@ Algorithm: Calculate Age in Days ## Algorithm 4: Temperature Converter **Pseudocode:** -```bash +``` Algorithm: Celsius to Fahrenheit Converter 1. Display "Enter temperature in Celsius: " 2. Get temperature in Celsius from user @@ -107,7 +107,7 @@ Algorithm: Celsius to Fahrenheit Converter 5. Display "°C = " 6. Display the Fahrenheit temperature 7. Display "°F" -```bash +``` **Your Task:** Create a temperature conversion program. @@ -116,7 +116,7 @@ Algorithm: Celsius to Fahrenheit Converter ## Algorithm 5: Rectangle Area Calculator **Pseudocode:** -```bash +``` Algorithm: Calculate Rectangle Area 1. Display "Rectangle Area Calculator" 2. Display "Enter length: " @@ -127,7 +127,7 @@ Algorithm: Calculate Rectangle Area 7. Calculate perimeter = 2 × (length + width) 8. Display "Area: " + area 9. Display "Perimeter: " + perimeter -```bash +``` **Your Task:** Create a program that calculates both area and perimeter. @@ -136,7 +136,7 @@ Algorithm: Calculate Rectangle Area ## Algorithm 6: Simple Interest Calculator **Pseudocode:** -```bash +``` Algorithm: Calculate Simple Interest 1. Display "Simple Interest Calculator" 2. Display "Enter principal amount: $" @@ -150,7 +150,7 @@ Algorithm: Calculate Simple Interest 10. Display "Principal: $" + principal 11. Display "Interest: $" + interest 12. Display "Total: $" + total -```bash +``` **Your Task:** Implement the complete interest calculation. @@ -211,7 +211,7 @@ Algorithm: Calculate Simple Interest ## Pseudocode Best Practices ### Good Pseudocode -```bash +``` Algorithm: Process User Data 1. Get user's name 2. Get user's age @@ -220,18 +220,18 @@ Algorithm: Process User Data Else Display "Minor user" 4. Display "Data processed" -```bash +``` ### Bad Pseudocode (Too Vague) -```bash +``` Algorithm: Do stuff 1. Get things 2. Calculate something 3. Show results -```bash +``` ### Good Pseudocode (Clear and Specific) -```bash +``` Algorithm: Calculate BMI 1. Display "BMI Calculator" 2. Display "Enter weight in kg: " @@ -240,7 +240,7 @@ Algorithm: Calculate BMI 5. Get height from user 6. Calculate BMI = weight ÷ (height × height) 7. Display "Your BMI is: " + BMI -```bash +``` --- @@ -257,13 +257,13 @@ Algorithm: Calculate BMI int main() { char name[50]; - + printf("Hello! What's your name? "); scanf("%s", name); - + printf("Nice to meet you, %s\n", name); printf("Welcome to programming!\n"); - + return 0; } ``` @@ -282,17 +282,17 @@ int main() { int main() { int num1, num2, sum; - + printf("Enter first number: "); scanf("%d", &num1); - + printf("Enter second number: "); scanf("%d", &num2); - + sum = num1 + num2; - + printf("The sum is: %d\n", sum); - + return 0; } ``` @@ -311,15 +311,15 @@ int main() { int main() { int age_years, age_days; - + printf("Enter your age in years: "); scanf("%d", &age_years); - + age_days = age_years * 365; - + printf("You are approximately %d days old\n", age_days); printf("That's a lot of days!\n"); - + return 0; } ``` @@ -338,14 +338,14 @@ int main() { int main() { float celsius, fahrenheit; - + printf("Enter temperature in Celsius: "); scanf("%f", &celsius); - + fahrenheit = (celsius * 9.0/5.0) + 32; - + printf("%.1f°C = %.1f°F\n", celsius, fahrenheit); - + return 0; } ``` @@ -364,20 +364,20 @@ int main() { int main() { float length, width, area, perimeter; - + printf("Rectangle Area Calculator\n"); printf("Enter length: "); scanf("%f", &length); - + printf("Enter width: "); scanf("%f", &width); - + area = length * width; perimeter = 2 * (length + width); - + printf("Area: %.2f\n", area); printf("Perimeter: %.2f\n", perimeter); - + return 0; } ``` @@ -396,24 +396,24 @@ int main() { int main() { float principal, rate, time, interest, total; - + printf("Simple Interest Calculator\n"); printf("Enter principal amount: $"); scanf("%f", &principal); - + printf("Enter interest rate (%%): "); scanf("%f", &rate); - + printf("Enter time in years: "); scanf("%f", &time); - + interest = (principal * rate * time) / 100; total = principal + interest; - + printf("Principal: $%.2f\n", principal); printf("Interest: $%.2f\n", interest); printf("Total: $%.2f\n", total); - + return 0; } ``` @@ -496,13 +496,13 @@ printf("Hello, %s!\n", name); --- -**Congratulations! You've translated your first pseudocode algorithms into working C programs!** +**Congratulations! You've translated your first pseudocode algorithms into working C programs!** *This is a major milestone - you're now thinking like a programmer! Next up: Variables in pseudocode!* ### How to Compile and Run -```bash +``` gcc main.c -o main ./main ``` diff --git a/lessons/c-c++/stage-2/level-2/lesson.md b/lessons/c-c++/stage-2/level-2/lesson.md index ede357a..ccbc6eb 100644 --- a/lessons/c-c++/stage-2/level-2/lesson.md +++ b/lessons/c-c++/stage-2/level-2/lesson.md @@ -42,7 +42,7 @@ Variables are the memory of your programs! Today you'll learn how to use variabl ## Algorithm 1: Shopping Cart Total **Pseudocode:** -```cpp +``` Algorithm: Calculate Shopping Total 1. Initialize total to 0 2. Initialize item_count to 0 @@ -55,7 +55,7 @@ Algorithm: Calculate Shopping Total d. Get next price from user 6. Display "Items purchased: " + item_count 7. Display "Total cost: $" + total -```cpp +``` **Variable Analysis:** - [ ] `total`: Accumulator (starts at 0, adds prices) @@ -69,7 +69,7 @@ Algorithm: Calculate Shopping Total ## Algorithm 2: Password Validation **Pseudocode:** -```cpp +``` Algorithm: Validate Password 1. Initialize attempts to 0 2. Initialize is_valid to false @@ -84,7 +84,7 @@ Algorithm: Validate Password a. Display "Access granted! " 6. Else: a. Display "Access denied! " -```cpp +``` **Variable Analysis:** - [ ] `attempts`: Counter (tracks login attempts) @@ -99,7 +99,7 @@ Algorithm: Validate Password ## Algorithm 3: Grade Average Calculator **Pseudocode:** -```cpp +``` Algorithm: Calculate Class Average 1. Initialize total_score to 0 2. Initialize student_count to 0 @@ -118,7 +118,7 @@ Algorithm: Calculate Class Average c. Display "Total students: " + student_count 6. Else: a. Display "No students entered" -```cpp +``` **Variable Analysis:** - [ ] `total_score`: Accumulator (sums all grades) @@ -134,7 +134,7 @@ Algorithm: Calculate Class Average ## Algorithm 4: Number Guessing Game **Pseudocode:** -```cpp +``` Algorithm: Number Guessing Game 1. Initialize secret_number to 42 2. Initialize guess_count to 0 @@ -153,7 +153,7 @@ Algorithm: Number Guessing Game ii. Else: i. Display "Too low! Try higher." 6. Display "Thanks for playing!" -```cpp +``` **Variable Analysis:** - [ ] `secret_number`: Constant (game target) @@ -168,7 +168,7 @@ Algorithm: Number Guessing Game ## Algorithm 5: Bank Account Simulator **Pseudocode:** -```cpp +``` Algorithm: Bank Account Manager 1. Initialize balance to 1000.00 2. Initialize transaction_count to 0 @@ -201,7 +201,7 @@ Algorithm: Bank Account Manager g. Else: i. Display "Invalid choice!" 7. Display "Thank you for banking with us!" -```cpp +``` **Variable Analysis:** - [ ] `balance`: Accumulator (changes with deposits/withdrawals) @@ -217,7 +217,7 @@ Algorithm: Bank Account Manager ## Algorithm 6: Temperature Tracker **Pseudocode:** -```cpp +``` Algorithm: Daily Temperature Tracker 1. Initialize day_count to 0 2. Initialize total_temperature to 0 @@ -240,7 +240,7 @@ Algorithm: Daily Temperature Tracker 11. Display "Highest: " + highest_temp + "°F" 12. Display "Lowest: " + lowest_temp + "°F" 13. Display "Readings taken: " + reading_count -```cpp +``` **Variable Analysis:** - [ ] `total_temperature`: Accumulator (sum of all readings) @@ -258,7 +258,7 @@ Algorithm: Daily Temperature Tracker **For each algorithm, track how variables change:** **Example for Algorithm 1:** -```cpp +``` Initial state: total = 0, item_count = 0 @@ -273,7 +273,7 @@ total = 15.75, item_count = 2 User enters: 0 (finish) Final state: total = 15.75, item_count = 2 -```cpp +``` --- @@ -306,25 +306,25 @@ total = 15.75, item_count = 2 ## Variable Patterns in Pseudocode ### Counter Variables -```cpp +``` Initialize counter to 0 While condition: Add 1 to counter // do something Display "Count: " + counter -```cpp +``` ### Accumulator Variables -```cpp +``` Initialize total to 0 While getting values: Get value from user Add value to total Display "Total: " + total -```cpp +``` ### Flag Variables -```cpp +``` Initialize is_valid to false // check conditions If condition met: @@ -333,16 +333,16 @@ If is_valid: Display "Success" Else: Display "Failed" -```cpp +``` ### Tracker Variables -```cpp +``` Initialize maximum to smallest possible value Initialize minimum to largest possible value For each value: If value > maximum: set maximum to value If value < minimum: set minimum to value -```cpp +``` --- @@ -361,24 +361,24 @@ int main() { float total = 0.0; int item_count = 0; float price; - + printf("Enter price of item 1 (or 0 to finish): "); scanf("%f", &price); - + while (price != 0) { total = total + price; item_count = item_count + 1; - + printf("Enter price of item %d (or 0 to finish): ", item_count + 1); scanf("%f", &price); } - + printf("Items purchased: %d\n", item_count); printf("Total cost: $%.2f\n", total); - + return 0; } -```cpp +``` **Variable Flow:** - [ ] `total`: Starts at 0, accumulates prices @@ -398,27 +398,27 @@ int main() { int is_valid = 0; // 0 = false, 1 = true char correct_password[] = "secret123"; char user_input[50]; - + while (attempts < 3 && is_valid == 0) { attempts = attempts + 1; - + printf("Enter password (attempt %d/3): ", attempts); scanf("%s", user_input); - + if (strcmp(user_input, correct_password) == 0) { is_valid = 1; } } - + if (is_valid == 1) { printf("Access granted! \n"); } else { printf("Access denied! \n"); } - + return 0; } -```cpp +``` **Key Concepts:** - [ ] String comparison with `strcmp()` @@ -437,11 +437,11 @@ int main() { int student_count = 0; int has_more_students = 1; // 1 = true, 0 = false float score; - + while (has_more_students == 1) { printf("Enter score for student %d (or -1 to finish): ", student_count + 1); scanf("%f", &score); - + if (score == -1) { has_more_students = 0; } else { @@ -449,7 +449,7 @@ int main() { student_count = student_count + 1; } } - + if (student_count > 0) { float average = total_score / student_count; printf("Class average: %.1f%%\n", average); @@ -457,10 +457,10 @@ int main() { } else { printf("No students entered\n"); } - + return 0; } -```cpp +``` **Variable Management:** - [ ] `total_score`: Accumulates all grades @@ -479,15 +479,15 @@ int main() { int guess_count = 0; int game_won = 0; // 0 = false, 1 = true int user_guess; - + printf("I'm thinking of a number between 1-100!\n"); - + while (game_won == 0) { guess_count = guess_count + 1; - + printf("Guess #%d: ", guess_count); scanf("%d", &user_guess); - + if (user_guess == secret_number) { game_won = 1; printf("Correct! You won in %d guesses! \n", guess_count); @@ -499,12 +499,12 @@ int main() { } } } - + printf("Thanks for playing!\n"); - + return 0; } -```cpp +``` **Game Logic:** - [ ] `game_won` flag controls the game loop @@ -524,15 +524,15 @@ int main() { int is_running = 1; // 1 = true, 0 = false int user_choice; float amount; - + printf("Welcome to Bank Account Manager\n"); printf("Initial balance: $%.2f\n", balance); - + while (is_running == 1) { printf("\n1. Deposit\n2. Withdraw\n3. Check Balance\n4. Exit\n"); printf("Enter choice: "); scanf("%d", &user_choice); - + if (user_choice == 1) { printf("Enter deposit amount: $"); scanf("%f", &amount); @@ -558,12 +558,12 @@ int main() { printf("Invalid choice!\n"); } } - + printf("Thank you for banking with us!\n"); - + return 0; } -```cpp +``` **Complex Variable Management:** - [ ] `balance`: Changes with deposits/withdrawals @@ -584,37 +584,37 @@ int main() { float lowest_temp = 1000.0; int reading_count = 0; float temperature; - + printf("Daily Temperature Tracker\n"); - + while (reading_count < 24) { reading_count = reading_count + 1; - + printf("Enter temperature reading #%d (°F): ", reading_count); scanf("%f", &temperature); - + total_temperature = total_temperature + temperature; - + if (temperature > highest_temp) { highest_temp = temperature; } - + if (temperature < lowest_temp) { lowest_temp = temperature; } } - + float average_temp = total_temperature / 24; - + printf("\nTemperature Summary:\n"); printf("Average: %.1f°F\n", average_temp); printf("Highest: %.1f°F\n", highest_temp); printf("Lowest: %.1f°F\n", lowest_temp); printf("Readings taken: %d\n", reading_count); - + return 0; } -```cpp +``` **Statistical Tracking:** - [ ] `highest_temp`: Tracks maximum value (initialized to very low) @@ -628,27 +628,27 @@ int main() { **Counters:** Always start at 0 ```c int count = 0; -```cpp +``` **Accumulators:** Usually start at 0 ```c float total = 0.0; -```cpp +``` **Flags:** Initialize to false/0 ```c int is_done = 0; -```cpp +``` **Maximum Trackers:** Initialize to minimum possible value ```c int max_value = INT_MIN; // or a very small number -```cpp +``` **Minimum Trackers:** Initialize to maximum possible value ```c int min_value = INT_MAX; // or a very large number -```cpp +``` ### Common Variable Mistakes @@ -656,13 +656,13 @@ int min_value = INT_MAX; // or a very large number ```c int sum; // Uninitialized - contains garbage value sum = sum + 5; // Undefined behavior! -```cpp +``` **Wrong Data Types:** ```c int average; // Wrong! Should be float for decimals average = 85.5; // Gets truncated to 85 -```cpp +``` **Scope Issues:** ```c @@ -670,11 +670,11 @@ if (condition) { int temp = 5; // Only exists in this block } // temp is undefined here! -```cpp +``` --- - **Excellent! You now understand how variables work in algorithms and code!** + **Excellent! You now understand how variables work in algorithms and code!** *Variables are the foundation of programming logic. Next: Mathematical operations in pseudocode! * @@ -700,50 +700,3 @@ Key functions and their purpose: - [ ] Main function: Entry point - [ ] Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```cpp -#include - -int main() { - printf("Hello, World!\n"); - return 0; -} -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard C++ conventions with proper imports and main function -2. **Output**: Uses printf to print messages to the console -3. **Standard Library**: Includes stdio.h for input/output operations -4. **Return Value**: Returns 0 to indicate successful execution -5. **Best Practices**: Code is readable and uses C++ idioms - -### Testing Your Solution - -1. **Compile**: `gcc main.c -o main` -2. **Run**: `./hello` -3. **Expected Output**: `Hello, World!` - -### Common Errors & Solutions - -| Error | Cause | Solution | -|-------|-------|----------| -| `command not found: gcc` | Compiler not installed | `sudo apt install gcc` (Ubuntu) | -| `undefined reference to main` | Missing main function | Ensure `int main()` exists | -| `error: implicit declaration of function 'printf'` | Missing stdio.h | Add `#include ` | - -### Tips for Learning - -- C uses stdio.h for input/output with additional features -- `printf` is the C standard for formatted output -- `\n` adds a newline character in format strings -- Format specifiers control how data is displayed (%d, %f, %s, etc.) diff --git a/lessons/c-c++/stage-2/level-3/lesson.md b/lessons/c-c++/stage-2/level-3/lesson.md index 1b63316..c08783b 100644 --- a/lessons/c-c++/stage-2/level-3/lesson.md +++ b/lessons/c-c++/stage-2/level-3/lesson.md @@ -42,7 +42,7 @@ Mathematics is the language of algorithms! Today you'll translate mathematical c ## Algorithm 1: Geometry Calculator **Pseudocode:** -```cpp +``` Algorithm: Calculate Circle Properties 1. Display "Circle Calculator" 2. Display "Enter radius: " @@ -54,7 +54,7 @@ Algorithm: Calculate Circle Properties 8. Display "Diameter: " + diameter 9. Display "Area: " + area 10. Display "Circumference: " + circumference -```cpp +``` **Mathematical Notes:** - [ ] π (pi) ≈ 3.14159 @@ -69,7 +69,7 @@ Algorithm: Calculate Circle Properties ## Algorithm 2: Right Triangle Solver **Pseudocode:** -```cpp +``` Algorithm: Solve Right Triangle 1. Display "Right Triangle Calculator" 2. Display "Enter side A: " @@ -84,7 +84,7 @@ Algorithm: Solve Right Triangle 11. Display "Hypotenuse: " + hypotenuse 12. Display "Area: " + area 13. Display "Perimeter: " + perimeter -```cpp +``` **Mathematical Notes:** - [ ] Pythagorean theorem: c² = a² + b² (where c is hypotenuse) @@ -98,7 +98,7 @@ Algorithm: Solve Right Triangle ## Algorithm 3: Compound Interest Calculator **Pseudocode:** -```cpp +``` Algorithm: Calculate Compound Interest 1. Display "Compound Interest Calculator" 2. Display "Enter principal amount: $" @@ -117,7 +117,7 @@ Algorithm: Calculate Compound Interest 15. Display "Principal: $" + principal 16. Display "Final Amount: $" + final_amount 17. Display "Total Interest: $" + total_interest -```cpp +``` **Mathematical Notes:** - [ ] Compound interest formula: A = P(1 + r/n)^(nt) @@ -131,7 +131,7 @@ Algorithm: Calculate Compound Interest ## Algorithm 4: Quadratic Equation Solver **Pseudocode:** -```cpp +``` Algorithm: Solve Quadratic Equation 1. Display "Quadratic Equation Solver" 2. Display "For equation ax² + bx + c = 0" @@ -152,7 +152,7 @@ Algorithm: Solve Quadratic Equation 12. Else: a. Display "No real roots (complex solutions)" 13. Display "Discriminant: " + discriminant -```cpp +``` **Mathematical Notes:** - [ ] Quadratic formula: x = [-b ± √(b² - 4ac)] / 2a @@ -166,7 +166,7 @@ Algorithm: Solve Quadratic Equation ## Algorithm 5: Fibonacci Sequence Generator **Pseudocode:** -```cpp +``` Algorithm: Generate Fibonacci Sequence 1. Display "Fibonacci Sequence Generator" 2. Display "Enter number of terms: " @@ -186,7 +186,7 @@ Algorithm: Generate Fibonacci Sequence d. Set second = next e. Add 1 to count 11. Display "Sequence complete" -```cpp +``` **Mathematical Notes:** - [ ] Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, ... @@ -200,7 +200,7 @@ Algorithm: Generate Fibonacci Sequence ## Algorithm 6: Statistical Calculator **Pseudocode:** -```cpp +``` Algorithm: Calculate Statistics 1. Display "Statistical Calculator" 2. Initialize sum = 0 @@ -226,7 +226,7 @@ Algorithm: Calculate Statistics g. Display "Standard Deviation: " + standard_deviation 8. Else: a. Display "No numbers entered" -```cpp +``` **Mathematical Notes:** - [ ] Mean (average): μ = Σx / n @@ -241,7 +241,7 @@ Algorithm: Calculate Statistics ## Algorithm 7: Distance Calculator (Coordinate Geometry) **Pseudocode:** -```cpp +``` Algorithm: Calculate Distance Between Points 1. Display "Distance Between Two Points" 2. Display "Enter coordinates for point 1:" @@ -260,7 +260,7 @@ Algorithm: Calculate Distance Between Points 15. Display "Point 1: (" + x1 + ", " + y1 + ")" 16. Display "Point 2: (" + x2 + ", " + y2 + ")" 17. Display "Distance: " + distance -```cpp +``` **Mathematical Notes:** - [ ] Distance formula: d = √[(x₂ - x₁)² + (y₂ - y₁)²] @@ -277,7 +277,7 @@ Algorithm: Calculate Distance Between Points ```c #include # include // For mathematical functions -```cpp +``` **Common Math Functions:** - [ ] `sqrt(x)` - Square root @@ -354,23 +354,23 @@ Algorithm: Calculate Distance Between Points int main() { float radius, area, circumference, diameter; const float PI = 3.14159; - + printf("Circle Calculator\n"); printf("Enter radius: "); scanf("%f", &radius); - + area = PI * radius * radius; circumference = 2 * PI * radius; diameter = 2 * radius; - + printf("Radius: %.2f\n", radius); printf("Diameter: %.2f\n", diameter); printf("Area: %.2f\n", area); printf("Circumference: %.2f\n", circumference); - + return 0; } -```cpp +``` **Key Concepts:** - [ ] Constant PI defined as `const float` @@ -387,26 +387,26 @@ int main() { int main() { float side_a, side_b, hypotenuse, area, perimeter; - + printf("Right Triangle Calculator\n"); printf("Enter side A: "); scanf("%f", &side_a); printf("Enter side B: "); scanf("%f", &side_b); - + hypotenuse = sqrt(side_a * side_a + side_b * side_b); area = (side_a * side_b) / 2; perimeter = side_a + side_b + hypotenuse; - + printf("Side A: %.2f\n", side_a); printf("Side B: %.2f\n", side_b); printf("Hypotenuse: %.2f\n", hypotenuse); printf("Area: %.2f\n", area); printf("Perimeter: %.2f\n", perimeter); - + return 0; } -```cpp +``` **Key Concepts:** - [ ] `#include ` for `sqrt()` function @@ -424,7 +424,7 @@ int main() { int main() { float principal, rate, years, frequency; float rate_decimal, total_compounds, compound_rate, final_amount, total_interest; - + printf("Compound Interest Calculator\n"); printf("Enter principal amount: $"); scanf("%f", &principal); @@ -434,21 +434,21 @@ int main() { scanf("%f", &years); printf("Enter compounding frequency (1=annual, 12=monthly): "); scanf("%f", &frequency); - + rate_decimal = rate / 100; total_compounds = years * frequency; compound_rate = rate_decimal / frequency; - + final_amount = principal * pow(1 + compound_rate, total_compounds); total_interest = final_amount - principal; - + printf("Principal: $%.2f\n", principal); printf("Final Amount: $%.2f\n", final_amount); printf("Total Interest: $%.2f\n", total_interest); - + return 0; } -```cpp +``` **Key Concepts:** - [ ] Complex compound interest formula @@ -465,7 +465,7 @@ int main() { int main() { float a, b, c, discriminant, root1, root2, root; - + printf("Quadratic Equation Solver\n"); printf("For equation ax² + bx + c = 0\n"); printf("Enter coefficient a: "); @@ -474,11 +474,11 @@ int main() { scanf("%f", &b); printf("Enter coefficient c: "); scanf("%f", &c); - + discriminant = b * b - 4 * a * c; - + printf("Discriminant: %.2f\n", discriminant); - + if (discriminant > 0) { root1 = (-b + sqrt(discriminant)) / (2 * a); root2 = (-b - sqrt(discriminant)) / (2 * a); @@ -489,10 +489,10 @@ int main() { } else { printf("No real roots (complex solutions)\n"); } - + return 0; } -```cpp +``` **Key Concepts:** - [ ] Discriminant determines number of roots @@ -508,34 +508,34 @@ int main() { int main() { int n, first = 0, second = 1, next, count = 3; - + printf("Fibonacci Sequence Generator\n"); printf("Enter number of terms: "); scanf("%d", &n); - + printf("Fibonacci sequence:\n"); - + if (n >= 1) { printf("%d ", first); } if (n >= 2) { printf("%d ", second); } - + while (count <= n) { next = first + second; printf("%d ", next); - + first = second; second = next; count++; } - + printf("\nSequence complete\n"); - + return 0; } -```cpp +``` **Key Concepts:** - [ ] Iterative Fibonacci calculation @@ -553,13 +553,13 @@ int main() { int main() { float sum = 0, sum_squares = 0, number, mean, variance, std_dev; int count = 0, has_more = 1; - + printf("Statistical Calculator\n"); - + while (has_more) { printf("Enter number %d (or 0 to finish): ", count + 1); scanf("%f", &number); - + if (number == 0) { has_more = 0; } else { @@ -568,12 +568,12 @@ int main() { sum_squares += number * number; } } - + if (count > 0) { mean = sum / count; variance = (sum_squares / count) - (mean * mean); std_dev = sqrt(variance); - + printf("Count: %d\n", count); printf("Sum: %.2f\n", sum); printf("Mean: %.2f\n", mean); @@ -581,10 +581,10 @@ int main() { } else { printf("No numbers entered\n"); } - + return 0; } -```cpp +``` **Key Concepts:** - [ ] Statistical formulas implementation @@ -601,31 +601,31 @@ int main() { int main() { float x1, y1, x2, y2, delta_x, delta_y, distance; - + printf("Distance Between Two Points\n"); printf("Enter coordinates for point 1:\n"); printf("X1: "); scanf("%f", &x1); printf("Y1: "); scanf("%f", &y1); - + printf("Enter coordinates for point 2:\n"); printf("X2: "); scanf("%f", &x2); printf("Y2: "); scanf("%f", &y2); - + delta_x = x2 - x1; delta_y = y2 - y1; distance = sqrt(delta_x * delta_x + delta_y * delta_y); - + printf("Point 1: (%.2f, %.2f)\n", x1, y1); printf("Point 2: (%.2f, %.2f)\n", x2, y2); printf("Distance: %.2f\n", distance); - + return 0; } -```cpp +``` **Key Concepts:** - [ ] Distance formula implementation @@ -641,7 +641,7 @@ int main() { const float PI = 3.14159265359; const float E = 2.71828182846; const float GRAVITY = 9.80665; -```cpp +``` **Precision Considerations:** - [ ] Use `double` for high-precision calculations @@ -657,7 +657,7 @@ result = 2 + 3 * 4; // Correct: (2 + 3) * 4 = 20 (parentheses force addition first) result = (2 + 3) * 4; -```cpp +``` **Integer Division:** ```c @@ -666,7 +666,7 @@ float result = 5 / 2; // Correct: 5.0 / 2 = 2.5 (float division) float result = 5.0 / 2; -```cpp +``` **Power Operations:** ```c @@ -675,11 +675,11 @@ result = 2 ^ 3; // Bitwise XOR, not power! // Correct: Use pow() function result = pow(2, 3); // 2^3 = 8 -```cpp +``` --- - **Fantastic! You've mastered mathematical algorithms in code!** + **Fantastic! You've mastered mathematical algorithms in code!** *Mathematics and programming are perfect partners. Next: Input/Output operations in pseudocode! * @@ -705,50 +705,3 @@ Key functions and their purpose: - [ ] Main function: Entry point - [ ] Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```cpp -#include - -int main() { - printf("Hello, World!\n"); - return 0; -} -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard C++ conventions with proper imports and main function -2. **Output**: Uses printf to print messages to the console -3. **Standard Library**: Includes stdio.h for input/output operations -4. **Return Value**: Returns 0 to indicate successful execution -5. **Best Practices**: Code is readable and uses C++ idioms - -### Testing Your Solution - -1. **Compile**: `gcc main.c -o main` -2. **Run**: `./hello` -3. **Expected Output**: `Hello, World!` - -### Common Errors & Solutions - -| Error | Cause | Solution | -|-------|-------|----------| -| `command not found: gcc` | Compiler not installed | `sudo apt install gcc` (Ubuntu) | -| `undefined reference to main` | Missing main function | Ensure `int main()` exists | -| `error: implicit declaration of function 'printf'` | Missing stdio.h | Add `#include ` | - -### Tips for Learning - -- C uses stdio.h for input/output with additional features -- `printf` is the C standard for formatted output -- `\n` adds a newline character in format strings -- Format specifiers control how data is displayed (%d, %f, %s, etc.) diff --git a/lessons/c-c++/stage-2/level-4/lesson.md b/lessons/c-c++/stage-2/level-4/lesson.md index f288279..fa6c927 100644 --- a/lessons/c-c++/stage-2/level-4/lesson.md +++ b/lessons/c-c++/stage-2/level-4/lesson.md @@ -31,7 +31,7 @@ User interaction is the heart of useful programs! Today you'll master the art of ## Algorithm 1: Age Verification System **Pseudocode:** -```cpp +``` Algorithm: Verify User Age 1. Display "=== Age Verification System ===" 2. Initialize is_valid_age to false @@ -51,7 +51,7 @@ Algorithm: Verify User Age a. Display " You are an adult!" 6. Else: a. Display " You are a minor." -```cpp +``` **Input/Output Focus:** - [ ] Input validation (numeric, range checking) @@ -66,7 +66,7 @@ Algorithm: Verify User Age ## Algorithm 2: Restaurant Menu System **Pseudocode:** -```cpp +``` Algorithm: Restaurant Ordering System 1. Display "=== Welcome to Code Café ===" 2. Initialize total_cost to 0 @@ -103,7 +103,7 @@ Algorithm: Restaurant Ordering System 9. Display "Tax (8%): $" + tax 10. Display "Final total: $" + final_total 11. Display "Thank you for your order! " -```cpp +``` **Input/Output Focus:** - [ ] Clear menu formatting @@ -118,7 +118,7 @@ Algorithm: Restaurant Ordering System ## Algorithm 3: Student Grade Manager **Pseudocode:** -```cpp +``` Algorithm: Student Grade Management 1. Display "=== Student Grade Manager ===" 2. Initialize grades array (can hold 100 grades) @@ -177,7 +177,7 @@ Algorithm: Student Grade Management i. Else: i. Display " Invalid choice! Please select 1-5." 6. Display "Thank you for using Grade Manager! " -```cpp +``` **Input/Output Focus:** - [ ] Array data storage @@ -192,7 +192,7 @@ Algorithm: Student Grade Management ## Algorithm 4: Unit Converter **Pseudocode:** -```cpp +``` Algorithm: Unit Conversion Calculator 1. Display "=== Unit Converter ===" 2. Initialize is_running to true @@ -248,7 +248,7 @@ Algorithm: Unit Conversion Calculator h. Else: i. Display " Invalid conversion type!" 4. Display "Thank you for using Unit Converter! " -```cpp +``` **Input/Output Focus:** - [ ] Nested menu systems @@ -263,7 +263,7 @@ Algorithm: Unit Conversion Calculator ## Algorithm 5: Survey Data Collector **Pseudocode:** -```cpp +``` Algorithm: Customer Satisfaction Survey 1. Display "=== Customer Satisfaction Survey ===" 2. Initialize responses array (can hold 50 responses) @@ -301,7 +301,7 @@ Algorithm: Customer Satisfaction Survey 7. Else: a. Display "No survey responses collected." 8. Display "Thank you for participating! " -```cpp +``` **Input/Output Focus:** - [ ] Clear survey instructions @@ -316,7 +316,7 @@ Algorithm: Customer Satisfaction Survey ## Algorithm 6: Library Book Tracker **Pseudocode:** -```cpp +``` Algorithm: Library Book Management 1. Display "=== Library Book Tracker ===" 2. Initialize books array (can hold 20 book titles) @@ -381,7 +381,7 @@ Algorithm: Library Book Management i. Else: i. Display " Invalid choice!" 6. Display "Thank you for using Library Book Tracker! " -```cpp +``` **Input/Output Focus:** - [ ] String array management @@ -403,7 +403,7 @@ if (input >= min_value && input <= max_value) { } else { // Invalid input - show error } -```cpp +``` **String Input Validation:** ```c @@ -413,7 +413,7 @@ if (strlen(input_string) > 0) { } else { // Empty input - show error } -```cpp +``` --- @@ -448,7 +448,7 @@ if (strlen(input_string) > 0) { ## User Interface Design Principles ### Clear Menu Design -```cpp +``` === Main Menu === 1. Add Item - Add new item to collection 2. View Items - Display all items @@ -457,7 +457,7 @@ if (strlen(input_string) > 0) { 5. Exit - Quit the program Enter choice (1-5): -```cpp +``` ### Error Message Best Practices - [ ] **Be specific**: "Grade must be between 0-100" not "Invalid input" @@ -487,12 +487,12 @@ Enter choice (1-5): int main() { int age_input; int is_valid_age = 0; - + printf("=== Age Verification System ===\n"); - + while (!is_valid_age) { printf("Please enter your age (0-120): "); - + if (scanf("%d", &age_input) != 1) { // Clear invalid input while (getchar() != '\n'); @@ -505,18 +505,18 @@ int main() { is_valid_age = 1; } } - + printf(" Age verified: %d years old\n", age_input); - + if (age_input >= 18) { printf(" You are an adult!\n"); } else { printf(" You are a minor.\n"); } - + return 0; } -```cpp +``` **Key Concepts:** - [ ] Input validation with `scanf()` return value checking @@ -534,9 +534,9 @@ int main() { float total_cost = 0.0; int order_complete = 0; int choice; - + printf("=== Welcome to Code Café ===\n"); - + while (!order_complete) { printf("\n1. Coffee - $3.50\n"); printf("2. Sandwich - $8.75\n"); @@ -545,7 +545,7 @@ int main() { printf("5. Complete Order\n"); printf("Enter your choice (1-5): "); scanf("%d", &choice); - + switch (choice) { case 1: total_cost += 3.50; @@ -571,20 +571,20 @@ int main() { break; } } - + printf("\n=== Order Summary ===\n"); printf("Total cost: $%.2f\n", total_cost); - + float tax = total_cost * 0.08; float final_total = total_cost + tax; - + printf("Tax (8%%): $%.2f\n", tax); printf("Final total: $%.2f\n", final_total); printf("Thank you for your order! \n"); - + return 0; } -```cpp +``` **Key Concepts:** - [ ] Switch statement for menu handling @@ -603,9 +603,9 @@ int main() { int grade_count = 0; int is_running = 1; int choice; - + printf("=== Student Grade Manager ===\n"); - + while (is_running) { printf("\n1. Add Grade\n"); printf("2. View All Grades\n"); @@ -614,14 +614,14 @@ int main() { printf("5. Exit\n"); printf("Choose an option (1-5): "); scanf("%d", &choice); - + switch (choice) { case 1: { if (grade_count < 100) { float new_grade; printf("Enter grade (0-100): "); scanf("%f", &new_grade); - + if (new_grade >= 0 && new_grade <= 100) { grades[grade_count] = new_grade; grade_count++; @@ -660,12 +660,12 @@ int main() { if (grade_count > 0) { float highest = grades[0]; float lowest = grades[0]; - + for (int i = 1; i < grade_count; i++) { if (grades[i] > highest) highest = grades[i]; if (grades[i] < lowest) lowest = grades[i]; } - + printf(" Highest: %.1f%%\n", highest); printf(" Lowest: %.1f%%\n", lowest); } else { @@ -680,12 +680,12 @@ int main() { break; } } - + printf("Thank you for using Grade Manager! \n"); - + return 0; } -```cpp +``` **Key Concepts:** - [ ] Array storage for multiple grades @@ -704,9 +704,9 @@ int main() { int is_running = 1; int conversion_type, direction; float value, result; - + printf("=== Unit Converter ===\n"); - + while (is_running) { printf("\n1. Temperature (°F ↔ °C)\n"); printf("2. Length (Feet ↔ Meters)\n"); @@ -714,14 +714,14 @@ int main() { printf("4. Exit\n"); printf("Select conversion type (1-4): "); scanf("%d", &conversion_type); - + if (conversion_type == 1) { printf("1. °F to °C\n2. °C to °F\n"); printf("Choose direction: "); scanf("%d", &direction); printf("Enter temperature: "); scanf("%f", &value); - + if (direction == 1) { result = (value - 32) * 5 / 9; printf("%.1f°F = %.1f°C\n", value, result); @@ -735,7 +735,7 @@ int main() { scanf("%d", &direction); printf("Enter length: "); scanf("%f", &value); - + if (direction == 1) { result = value * 0.3048; printf("%.2f ft = %.2f m\n", value, result); @@ -749,7 +749,7 @@ int main() { scanf("%d", &direction); printf("Enter weight: "); scanf("%f", &value); - + if (direction == 1) { result = value * 0.4536; printf("%.2f lbs = %.2f kg\n", value, result); @@ -763,12 +763,12 @@ int main() { printf(" Invalid conversion type!\n"); } } - + printf("Thank you for using Unit Converter! \n"); - + return 0; } -```cpp +``` **Key Concepts:** - [ ] Nested menu system @@ -788,9 +788,9 @@ int main() { int response_count = 0; int survey_complete = 0; int rating; - + printf("=== Customer Satisfaction Survey ===\n"); - + while (!survey_complete) { printf("\nParticipant #%d\n", response_count + 1); printf("Rate your satisfaction (1-5):\n"); @@ -801,7 +801,7 @@ int main() { printf("5 = Very Satisfied\n"); printf("Enter rating (1-5, or 0 to finish survey): "); scanf("%d", &rating); - + if (rating == 0) { survey_complete = 1; } else if (rating >= 1 && rating <= 5) { @@ -812,38 +812,38 @@ int main() { printf(" Invalid rating! Please enter 1-5 or 0 to finish.\n"); } } - + if (response_count > 0) { printf("\n=== Survey Results ===\n"); printf("Total responses: %d\n", response_count); - + int counts[6] = {0}; // Index 1-5 for ratings - + for (int i = 0; i < response_count; i++) { counts[responses[i]]++; } - + for (int rating = 1; rating <= 5; ratingcc) { float percentage = (float)counts[rating] / response_count * 100; printf("%d: %d responses (%.1f%%)\n", rating, counts[rating], percentage); } - + float sum = 0; for (int i = 0; i < response_count; i++) { sum += responses[i]; } float average = sum / response_count; - + printf("Average satisfaction: %.1f/5.0\n", average); } else { printf("No survey responses collected.\n"); } - + printf("Thank you for participating! \n"); - + return 0; } -```cpp +``` **Key Concepts:** - [ ] Array storage for survey responses @@ -864,9 +864,9 @@ int main() { int book_count = 0; int is_running = 1; int choice; - + printf("=== Library Book Tracker ===\n"); - + while (is_running) { printf("\n1. Add Book\n"); printf("2. List All Books\n"); @@ -875,7 +875,7 @@ int main() { printf("5. Exit\n"); printf("Choose option (1-5): "); scanf("%d", &choice); - + switch (choice) { case 1: { if (book_count < 20) { @@ -883,10 +883,10 @@ int main() { printf("Enter book title: "); getchar(); // Clear newline fgets(book_title, sizeof(book_title), stdin); - + // Remove trailing newline book_title[strcspn(book_title, "\n")] = '\0'; - + if (strlen(book_title) > 0) { strcpy(books[book_count], book_title); book_count++; @@ -916,7 +916,7 @@ int main() { getchar(); // Clear newline fgets(search_term, sizeof(search_term), stdin); search_term[strcspn(search_term, "\n")] = '\0'; - + int found_count = 0; for (int i = 0; i < book_count; i++) { if (strstr(books[i], search_term) != NULL) { @@ -924,7 +924,7 @@ int main() { found_count++; } } - + if (found_count == 0) { printf(" No books found matching '%s'\n", search_term); } @@ -938,15 +938,15 @@ int main() { int book_number; printf("Enter book number to remove (1-%d): ", book_count); scanf("%d", &book_number); - + if (book_number >= 1 && book_number <= book_count) { printf("Removing: '%s'\n", books[book_number - 1]); - + // Shift remaining books left for (int i = book_number - 1; i < book_count - 1; i++) { strcpy(books[i], books[i + 1]); } - + book_count--; printf(" Book removed successfully!\n"); } else { @@ -965,12 +965,12 @@ int main() { break; } } - + printf("Thank you for using Library Book Tracker! \n"); - + return 0; } -```cpp +``` **Key Concepts:** - [ ] 2D array for string storage @@ -988,7 +988,7 @@ int main() { // After scanf, clear remaining input int c; while ((c = getchar()) != '\n' && c != EOF); -```cpp +``` **Reading Full Lines:** ```c @@ -996,7 +996,7 @@ char buffer[100]; fgets(buffer, sizeof(buffer), stdin); // Remove trailing newline buffer[strcspn(buffer, "\n")] = '\0'; -```cpp +``` **Input Validation Patterns:** ```c @@ -1012,11 +1012,11 @@ int get_valid_number(int min, int max) { } while (value < min || value > max); return value; } -```cpp +``` --- - **Excellent! You've mastered user interaction and I/O operations!** + **Excellent! You've mastered user interaction and I/O operations!** *Programs that talk to users are much more useful. Next: Decision-making in pseudocode! * @@ -1042,50 +1042,3 @@ Key functions and their purpose: - [ ] Main function: Entry point - [ ] Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```cpp -#include - -int main() { - printf("Hello, World!\n"); - return 0; -} -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard C++ conventions with proper imports and main function -2. **Output**: Uses printf to print messages to the console -3. **Standard Library**: Includes stdio.h for input/output operations -4. **Return Value**: Returns 0 to indicate successful execution -5. **Best Practices**: Code is readable and uses C++ idioms - -### Testing Your Solution - -1. **Compile**: `gcc main.c -o main` -2. **Run**: `./hello` -3. **Expected Output**: `Hello, World!` - -### Common Errors & Solutions - -| Error | Cause | Solution | -|-------|-------|----------| -| `command not found: gcc` | Compiler not installed | `sudo apt install gcc` (Ubuntu) | -| `undefined reference to main` | Missing main function | Ensure `int main()` exists | -| `error: implicit declaration of function 'printf'` | Missing stdio.h | Add `#include ` | - -### Tips for Learning - -- C uses stdio.h for input/output with additional features -- `printf` is the C standard for formatted output -- `\n` adds a newline character in format strings -- Format specifiers control how data is displayed (%d, %f, %s, etc.) diff --git a/lessons/c-c++/stage-2/level-5/lesson.md b/lessons/c-c++/stage-2/level-5/lesson.md index ad52d04..7a6e3c6 100644 --- a/lessons/c-c++/stage-2/level-5/lesson.md +++ b/lessons/c-c++/stage-2/level-5/lesson.md @@ -48,7 +48,7 @@ Decision-making is the intelligence of programs! Today you'll master complex con ## Algorithm 1: Loan Approval System **Pseudocode:** -```cpp +``` Algorithm: Evaluate Loan Application 1. Display "=== Loan Approval System ===" 2. Display "Enter applicant's age: " @@ -97,7 +97,7 @@ Algorithm: Evaluate Loan Application 22. Else: a. Display " LOAN DENIED" b. Display "Reason: " + approval_status -```cpp +``` **Decision Logic:** - [ ] Age restrictions (18-70) @@ -113,7 +113,7 @@ Algorithm: Evaluate Loan Application ## Algorithm 2: Health Risk Assessment **Pseudocode:** -```cpp +``` Algorithm: Assess Health Risk Factors 1. Display "=== Health Risk Assessment ===" 2. Display "Enter your age: " @@ -172,7 +172,7 @@ Algorithm: Assess Health Risk Factors 37. Else: a. Display " LOW RISK - Maintain healthy lifestyle" b. Display "Recommendations: Continue current healthy habits" -```cpp +``` **Decision Logic:** - [ ] Multi-factor risk assessment @@ -187,7 +187,7 @@ Algorithm: Assess Health Risk Factors ## Algorithm 3: Academic Standing Calculator **Pseudocode:** -```cpp +``` Algorithm: Determine Academic Standing 1. Display "=== Academic Standing Calculator ===" 2. Display "Enter GPA (0.0-4.0): " @@ -237,7 +237,7 @@ Algorithm: Determine Academic Standing a. Display " Limited eligibility - Academic plan required" 23. Else: a. Display " Counseling required - Contact academic advisor" -```cpp +``` **Decision Logic:** - [ ] Multi-criteria academic evaluation @@ -252,7 +252,7 @@ Algorithm: Determine Academic Standing ## Algorithm 4: Insurance Premium Calculator **Pseudocode:** -```cpp +``` Algorithm: Calculate Insurance Premium 1. Display "=== Auto Insurance Premium Calculator ===" 2. Display "Enter driver's age: " @@ -306,7 +306,7 @@ Algorithm: Calculate Insurance Premium 36. Else: a. Display " LOW RISK PROFILE" b. Display "Eligible for premium discounts" -```cpp +``` **Decision Logic:** - [ ] Multi-factor risk assessment @@ -321,7 +321,7 @@ Algorithm: Calculate Insurance Premium ## Algorithm 5: Travel Itinerary Planner **Pseudocode:** -```cpp +``` Algorithm: Plan Travel Itinerary 1. Display "=== Travel Itinerary Planner ===" 2. Display "Enter destination city: " @@ -385,7 +385,7 @@ Algorithm: Plan Travel Itinerary a. Display " Budget exceeded by $" + (total_budget - daily_budget × trip_days) 38. Else: a. Display " Within budget - $" + (daily_budget × trip_days - total_budget) + " remaining" -```cpp +``` **Decision Logic:** - [ ] Seasonal activity recommendations @@ -400,7 +400,7 @@ Algorithm: Plan Travel Itinerary ## Algorithm 6: Employee Performance Review **Pseudocode:** -```cpp +``` Algorithm: Evaluate Employee Performance 1. Display "=== Employee Performance Review ===" 2. Display "Enter employee name: " @@ -460,7 +460,7 @@ Algorithm: Evaluate Employee Performance 31. Else: a. Display " Performance review complete" b. Display "Continue professional development" -```cpp +``` **Decision Logic:** - [ ] Multi-criteria performance evaluation @@ -475,7 +475,7 @@ Algorithm: Evaluate Employee Performance ### Decision Tree Patterns **Eligibility Checking:** -```cpp +``` If primary_condition AND secondary_condition: If qualifying_factor: APPROVE @@ -483,19 +483,19 @@ If primary_condition AND secondary_condition: DENY Else: DENY -```cpp +``` **Risk Assessment:** -```cpp +``` Initialize risk_score = 0 For each risk_factor: If factor_present: Add points to risk_score Categorize based on total_score -```cpp +``` **Multi-tier Classification:** -```cpp +``` If score >= threshold_A: If sub_condition: CATEGORY_A_PLUS @@ -505,7 +505,7 @@ Else if score >= threshold_B: CATEGORY_B Else: CATEGORY_C -```cpp +``` --- @@ -553,7 +553,7 @@ ApplicationState evaluate_application(ApplicationData data) { if (data.income > 50000 && data.score > 700) return STATE_APPROVED; return STATE_PROCESSING; } -```cpp +``` ### Rule Engine Pattern ```c @@ -566,7 +566,7 @@ int evaluate_rules(DataItem item, Rule* rules, int rule_count) { } return score; } -```cpp +``` ### Decision Table Pattern ```c @@ -576,7 +576,7 @@ int evaluate_rules(DataItem item, Rule* rules, int rule_count) { // >=25| <30k | <600 | Deny // >=25| >=30k | >=600 | Approve // >=25| <30k | >=600 | Review -```cpp +``` --- @@ -596,7 +596,7 @@ int main() { float income, loan_amount; char approval_status[50] = "PENDING"; float max_loan_amount = 0.0; - + printf("=== Loan Approval System ===\n"); printf("Enter applicant's age: "); scanf("%d", &age); @@ -606,7 +606,7 @@ int main() { scanf("%d", &credit_score); printf("Enter loan amount requested: $"); scanf("%f", &loan_amount); - + if (age < 18) { strcpy(approval_status, "DENIED - Underage"); } else if (age > 70) { @@ -624,7 +624,7 @@ int main() { } else { max_loan_amount = income * 1; } - + if (loan_amount > max_loan_amount) { strcpy(approval_status, "DENIED - Loan amount exceeds limit"); } else if (loan_amount > income * 0.5) { @@ -634,13 +634,13 @@ int main() { } } } - + printf("\n=== Loan Decision ===\n"); printf("Applicant age: %d\n", age); printf("Annual income: $%.2f\n", income); printf("Credit score: %d\n", credit_score); printf("Loan requested: $%.2f\n", loan_amount); - + if (strcmp(approval_status, "APPROVED") == 0) { printf(" LOAN APPROVED!\n"); printf("Maximum approved amount: $%.2f\n", max_loan_amount); @@ -651,10 +651,10 @@ int main() { printf(" LOAN DENIED\n"); printf("Reason: %s\n", approval_status); } - + return 0; } -```cpp +``` **Key Concepts:** - [ ] Complex nested conditional logic @@ -675,7 +675,7 @@ int main() { float bmi; char smoking_status[10], exercise_status[10], family_history[10]; char risk_level[20] = "LOW"; - + printf("=== Health Risk Assessment ===\n"); printf("Enter your age: "); scanf("%d", &age); @@ -687,27 +687,27 @@ int main() { scanf("%s", exercise_status); printf("Family history of heart disease? (yes/no): "); scanf("%s", family_history); - + // Age risk if (age >= 65) risk_points += 3; else if (age >= 45) risk_points += 2; else if (age >= 30) risk_points += 1; - + // BMI risk if (bmi >= 30) risk_points += 3; else if (bmi >= 25) risk_points += 2; else if (bmi >= 23) risk_points += 1; - + // Lifestyle risk if (strcmp(smoking_status, "yes") == 0) risk_points += 3; if (strcmp(exercise_status, "no") == 0) risk_points += 2; if (strcmp(family_history, "yes") == 0) risk_points += 2; - + // Determine risk level if (risk_points >= 8) strcpy(risk_level, "HIGH"); else if (risk_points >= 5) strcpy(risk_level, "MODERATE"); else if (risk_points >= 3) strcpy(risk_level, "ELEVATED"); - + printf("\n=== Health Risk Assessment Results ===\n"); printf("Age: %d years\n", age); printf("BMI: %.1f\n", bmi); @@ -716,7 +716,7 @@ int main() { printf("Family history: %s\n", family_history); printf("Risk points: %d/12\n", risk_points); printf("Risk level: %s\n", risk_level); - + if (strcmp(risk_level, "HIGH") == 0) { printf(" HIGH RISK - Consult doctor immediately\n"); printf("Recommendations: Lifestyle changes, medical evaluation\n"); @@ -730,10 +730,10 @@ int main() { printf(" LOW RISK - Maintain healthy lifestyle\n"); printf("Recommendations: Continue current healthy habits\n"); } - + return 0; } -```cpp +``` **Key Concepts:** - [ ] Point-based risk assessment system @@ -755,7 +755,7 @@ int main() { char probation_status[10]; char standing[50] = "UNDETERMINED"; char eligibility_status[30] = "ELIGIBLE"; - + printf("=== Academic Standing Calculator ===\n"); printf("Enter GPA (0.0-4.0): "); scanf("%f", &gpa); @@ -765,7 +765,7 @@ int main() { scanf("%d", &semesters); printf("Any academic probation? (yes/no): "); scanf("%s", probation_status); - + if (strcmp(probation_status, "yes") == 0) { strcpy(standing, "ACADEMIC PROBATION"); strcpy(eligibility_status, "RESTRICTED"); @@ -793,7 +793,7 @@ int main() { strcpy(eligibility_status, "COUNSELING REQUIRED"); } } - + printf("\n=== Academic Assessment ===\n"); printf("GPA: %.2f\n", gpa); printf("Credit Hours: %d\n", credit_hours); @@ -801,7 +801,7 @@ int main() { printf("Probation Status: %s\n", probation_status); printf("Academic Standing: %s\n", standing); printf("Eligibility Status: %s\n", eligibility_status); - + if (strcmp(eligibility_status, "ELIGIBLE") == 0) { printf(" Eligible for all academic activities\n"); } else if (strcmp(eligibility_status, "RESTRICTED") == 0) { @@ -809,10 +809,10 @@ int main() { } else { printf(" Counseling required - Contact academic advisor\n"); } - + return 0; } -```cpp +``` **Key Concepts:** - [ ] Multi-criteria academic evaluation @@ -832,7 +832,7 @@ int main() { int age, experience, mileage; char vehicle_type[20], accident_history[10]; float base_premium = 500.0, risk_multiplier = 1.0, final_premium; - + printf("=== Auto Insurance Premium Calculator ===\n"); printf("Enter driver's age: "); scanf("%d", &age); @@ -844,29 +844,29 @@ int main() { scanf("%s", accident_history); printf("Annual mileage: "); scanf("%d", &mileage); - + // Age risk if (age < 25) risk_multiplier *= 1.5; else if (age > 65) risk_multiplier *= 1.2; - + // Experience risk if (experience < 3) risk_multiplier *= 1.4; else if (experience > 10) risk_multiplier *= 0.9; - + // Vehicle type risk if (strcmp(vehicle_type, "sports") == 0) risk_multiplier *= 1.8; else if (strcmp(vehicle_type, "suv") == 0) risk_multiplier *= 1.3; else if (strcmp(vehicle_type, "truck") == 0) risk_multiplier *= 1.1; - + // Accident history if (strcmp(accident_history, "yes") == 0) risk_multiplier *= 1.6; - + // Mileage risk if (mileage > 15000) risk_multiplier *= 1.2; else if (mileage < 5000) risk_multiplier *= 0.95; - + final_premium = base_premium * risk_multiplier; - + printf("\n=== Premium Calculation ===\n"); printf("Driver Age: %d\n", age); printf("Driving Experience: %d years\n", experience); @@ -876,7 +876,7 @@ int main() { printf("Base Premium: $%.2f\n", base_premium); printf("Risk Multiplier: %.2f\n", risk_multiplier); printf("Final Premium: $%.2f\n", final_premium); - + if (risk_multiplier > 2.0) { printf(" HIGH RISK PROFILE\n"); printf("Consider defensive driving courses\n"); @@ -887,10 +887,10 @@ int main() { printf(" LOW RISK PROFILE\n"); printf("Eligible for premium discounts\n"); } - + return 0; } -```cpp +``` **Key Concepts:** - [ ] Cumulative risk multiplier system @@ -911,7 +911,7 @@ int main() { int trip_days, group_size, activity_count = 0; float daily_budget, total_cost = 0.0; float accommodation_cost, food_cost, activity_cost, transportation_cost, miscellaneous_cost, total_budget; - + printf("=== Travel Itinerary Planner ===\n"); printf("Enter destination city: "); scanf("%s", destination); @@ -923,7 +923,7 @@ int main() { scanf("%s", season); printf("Group size: "); scanf("%d", &group_size); - + // Seasonal activity planning if (strcmp(season, "summer") == 0) { if (strstr(destination, "beach") != NULL || strstr(destination, "Beach") != NULL) { @@ -950,7 +950,7 @@ int main() { total_cost += 35; activity_count = 4; } - + // Cost calculations accommodation_cost = daily_budget * 0.4 * trip_days; food_cost = daily_budget * 0.3 * trip_days; @@ -958,14 +958,14 @@ int main() { transportation_cost = daily_budget * 0.2 * trip_days; miscellaneous_cost = daily_budget * 0.1 * trip_days; total_budget = accommodation_cost + food_cost + activity_cost + transportation_cost + miscellaneous_cost; - + // Group discount if (group_size > 4) { float group_discount = total_budget * 0.1; total_budget -= group_discount; printf(" Group discount applied: $%.2f\n", group_discount); } - + printf("\n=== Travel Itinerary ===\n"); printf("Destination: %s\n", destination); printf("Duration: %d days\n", trip_days); @@ -979,17 +979,17 @@ int main() { printf("Transportation: $%.2f\n", transportation_cost); printf("Miscellaneous: $%.2f\n", miscellaneous_cost); printf("Total Estimated Cost: $%.2f\n", total_budget); - + float budget_limit = daily_budget * trip_days; if (total_budget > budget_limit) { printf(" Budget exceeded by $%.2f\n", total_budget - budget_limit); } else { printf(" Within budget - $%.2f remaining\n", budget_limit - total_budget); } - + return 0; } -```cpp +``` **Key Concepts:** - [ ] Seasonal activity recommendations @@ -1010,7 +1010,7 @@ int main() { int years_service, productivity, quality, teamwork; float average_score, salary_adjustment = 0.0; char performance_rating[30] = "UNDETERMINED"; - + printf("=== Employee Performance Review ===\n"); printf("Enter employee name: "); scanf("%s", employee_name); @@ -1024,9 +1024,9 @@ int main() { scanf("%d", &teamwork); printf("Any disciplinary actions? (yes/no): "); scanf("%s", disciplinary_status); - + average_score = (productivity + quality + teamwork) / 3.0; - + if (strcmp(disciplinary_status, "yes") == 0) { strcpy(performance_rating, "UNSATISFACTORY"); salary_adjustment = -5.0; @@ -1053,7 +1053,7 @@ int main() { salary_adjustment = 0.0; } } - + printf("\n=== Performance Review Results ===\n"); printf("Employee: %s\n", employee_name); printf("Years of Service: %d\n", years_service); @@ -1064,7 +1064,7 @@ int main() { printf("Disciplinary Actions: %s\n", disciplinary_status); printf("Performance Rating: %s\n", performance_rating); printf("Salary Adjustment: %.1f%%\n", salary_adjustment); - + if (strcmp(performance_rating, "OUTSTANDING") == 0) { printf(" EMPLOYEE OF THE YEAR CANDIDATE\n"); printf("Eligible for bonus and promotion consideration\n"); @@ -1075,10 +1075,10 @@ int main() { printf(" Performance review complete\n"); printf("Continue professional development\n"); } - + return 0; } -```cpp +``` **Key Concepts:** - [ ] Multi-criteria performance evaluation @@ -1105,7 +1105,7 @@ if (age >= 18) { } } } -```cpp +``` **Consistent Structure:** ```c @@ -1117,7 +1117,7 @@ if (condition1) { } else { // handle default case } -```cpp +``` **Early Returns:** ```c @@ -1127,11 +1127,11 @@ if (invalid_input) { return; } // continue with valid input -```cpp +``` --- - **Brilliant! You've mastered complex decision-making in code!** + **Brilliant! You've mastered complex decision-making in code!** *Programs can now make intelligent decisions like real applications. Next: Loop algorithms in pseudocode! * @@ -1157,50 +1157,3 @@ Key functions and their purpose: - [ ] Main function: Entry point - [ ] Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```cpp -#include - -int main() { - printf("Hello, World!\n"); - return 0; -} -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard C++ conventions with proper imports and main function -2. **Output**: Uses printf to print messages to the console -3. **Standard Library**: Includes stdio.h for input/output operations -4. **Return Value**: Returns 0 to indicate successful execution -5. **Best Practices**: Code is readable and uses C++ idioms - -### Testing Your Solution - -1. **Compile**: `gcc main.c -o main` -2. **Run**: `./hello` -3. **Expected Output**: `Hello, World!` - -### Common Errors & Solutions - -| Error | Cause | Solution | -|-------|-------|----------| -| `command not found: gcc` | Compiler not installed | `sudo apt install gcc` (Ubuntu) | -| `undefined reference to main` | Missing main function | Ensure `int main()` exists | -| `error: implicit declaration of function 'printf'` | Missing stdio.h | Add `#include ` | - -### Tips for Learning - -- C uses stdio.h for input/output with additional features -- `printf` is the C standard for formatted output -- `\n` adds a newline character in format strings -- Format specifiers control how data is displayed (%d, %f, %s, etc.) diff --git a/lessons/c-c++/stage-2/level-6/lesson.md b/lessons/c-c++/stage-2/level-6/lesson.md index bc4533b..969be4d 100644 --- a/lessons/c-c++/stage-2/level-6/lesson.md +++ b/lessons/c-c++/stage-2/level-6/lesson.md @@ -48,7 +48,7 @@ Loops are the workhorses of programming! Today you'll master algorithms that use ## Algorithm 1: Sales Data Analyzer **Pseudocode:** -```cpp +``` Algorithm: Analyze Monthly Sales Data 1. Display "=== Sales Data Analyzer ===" 2. Initialize sales array (can hold 30 values) @@ -85,7 +85,7 @@ Algorithm: Analyze Monthly Sales Data i. Display "Day " + (i + 1) + ": $" + sales[i] 10. Else: a. Display "No sales data entered." -```cpp +``` **Loop Logic:** - [ ] Input loop with validation @@ -100,7 +100,7 @@ Algorithm: Analyze Monthly Sales Data ## Algorithm 2: Student Attendance Tracker **Pseudocode:** -```cpp +``` Algorithm: Track Class Attendance 1. Display "=== Class Attendance Tracker ===" 2. Display "Enter number of students: " @@ -133,7 +133,7 @@ Algorithm: Track Class Attendance i. Display "Student " + student + ": Present" b. Else: i. Display "Student " + student + ": Absent" -```cpp +``` **Loop Logic:** - [ ] Fixed iteration for known number of students @@ -148,7 +148,7 @@ Algorithm: Track Class Attendance ## Algorithm 3: Inventory Management System **Pseudocode:** -```cpp +``` Algorithm: Manage Store Inventory 1. Display "=== Inventory Management System ===" 2. Initialize item_names array (can hold 50 items) @@ -222,7 +222,7 @@ Algorithm: Manage Store Inventory i. Else: i. Display " Invalid choice!" 7. Display "Thank you for using Inventory Management System! " -```cpp +``` **Loop Logic:** - [ ] Menu-driven interface with multiple operations @@ -237,7 +237,7 @@ Algorithm: Manage Store Inventory ## Algorithm 4: Grade Book Calculator **Pseudocode:** -```cpp +``` Algorithm: Calculate Final Grades 1. Display "=== Grade Book Calculator ===" 2. Display "Enter number of students: " @@ -294,7 +294,7 @@ Algorithm: Calculate Final Grades 23. Display "C grades: " + grade_ranges[2] 24. Display "D grades: " + grade_ranges[3] 25. Display "F grades: " + grade_ranges[4] -```cpp +``` **Loop Logic:** - [ ] 2D array processing (nested loops) @@ -309,7 +309,7 @@ Algorithm: Calculate Final Grades ## Algorithm 5: Password Generator **Pseudocode:** -```cpp +``` Algorithm: Generate Secure Passwords 1. Display "=== Password Generator ===" 2. Display "Enter desired password length (8-20): " @@ -347,7 +347,7 @@ Algorithm: Generate Secure Passwords 23. If include_special is "y": a. Display " Special characters" 24. Display " Lowercase letters (always included)" -```cpp +``` **Loop Logic:** - [ ] Input validation loop @@ -362,7 +362,7 @@ Algorithm: Generate Secure Passwords ## Algorithm 6: Voting System **Pseudocode:** -```cpp +``` Algorithm: Conduct Election Voting 1. Display "=== Election Voting System ===" 2. Initialize candidate_names array ["Alice", "Bob", "Charlie"] @@ -407,7 +407,7 @@ Algorithm: Conduct Election Voting ii. Display candidate_names[i] + ": " + votes[i] + " votes (" + percentage + "%)" 8. Else: a. Display "No votes were cast." -```cpp +``` **Loop Logic:** - [ ] Menu-driven voting interface @@ -465,25 +465,25 @@ Algorithm: Conduct Election Voting ## Loop Algorithm Patterns ### Accumulation Pattern -```cpp +``` Initialize total to 0 While getting values: Get next_value Add next_value to total Display "Total: " + total -```cpp +``` ### Counting Pattern -```cpp +``` Initialize count to 0 For each item: If item meets criteria: Add 1 to count Display "Count: " + count -```cpp +``` ### Search Pattern -```cpp +``` Initialize found to false For each item in collection: If item matches target: @@ -494,10 +494,10 @@ If found: Display "Found at location" Else: Display "Not found" -```cpp +``` ### Validation Pattern -```cpp +``` Initialize is_valid to false While not is_valid: Get user_input @@ -506,7 +506,7 @@ While not is_valid: Else: Display error message Process valid input -```cpp +``` --- @@ -525,22 +525,22 @@ int main() { float sales[30]; int sales_count = 0; float total_sales = 0.0, highest_sale = 0.0, lowest_sale = 999999.0; - + printf("=== Sales Data Analyzer ===\n"); printf("Enter daily sales (enter -1 to finish):\n"); - + while (sales_count < 30) { printf("Day %d: $", sales_count + 1); float daily_sale; scanf("%f", &daily_sale); - + if (daily_sale == -1) { break; } else if (daily_sale >= 0) { sales[sales_count] = daily_sale; total_sales += daily_sale; sales_count++; - + if (daily_sale > highest_sale) { highest_sale = daily_sale; } @@ -551,17 +551,17 @@ int main() { printf(" Invalid sale amount! Please enter positive number.\n"); } } - + if (sales_count > 0) { float average_sale = total_sales / sales_count; - + printf("\n=== Sales Summary ===\n"); printf("Total days: %d\n", sales_count); printf("Total sales: $%.2f\n", total_sales); printf("Average daily sales: $%.2f\n", average_sale); printf("Highest sale: $%.2f\n", highest_sale); printf("Lowest sale: $%.2f\n", lowest_sale); - + printf("\n=== Daily Breakdown ===\n"); for (int i = 0; i < sales_count; i++) { printf("Day %d: $%.2f\n", i + 1, sales[i]); @@ -569,10 +569,10 @@ int main() { } else { printf("No sales data entered.\n"); } - + return 0; } -```cpp +``` **Key Concepts:** - [ ] Array storage for sales data @@ -591,18 +591,18 @@ int main() { int main() { int num_students, present_count = 0; char attendance_status[10]; - + printf("=== Class Attendance Tracker ===\n"); printf("Enter number of students: "); scanf("%d", &num_students); - + // Using array for attendance (1 = present, 0 = absent) int attendance[100]; // Assuming max 100 students - + for (int student = 1; student <= num_students; student++) { printf("Student %d present? (y/n): ", student); scanf("%s", attendance_status); - + if (strcmp(attendance_status, "y") == 0 || strcmp(attendance_status, "Y") == 0) { attendance[student - 1] = 1; present_count++; @@ -610,15 +610,15 @@ int main() { attendance[student - 1] = 0; } } - + float attendance_percentage = (float)present_count / num_students * 100; - + printf("\n=== Attendance Report ===\n"); printf("Total students: %d\n", num_students); printf("Present: %d\n", present_count); printf("Absent: %d\n", num_students - present_count); printf("Attendance rate: %.1f%%\n", attendance_percentage); - + if (attendance_percentage >= 90) { printf(" Excellent attendance!\n"); } else if (attendance_percentage >= 75) { @@ -626,7 +626,7 @@ int main() { } else { printf(" Poor attendance - follow up required\n"); } - + printf("\n=== Individual Status ===\n"); for (int student = 1; student <= num_students; student++) { if (attendance[student - 1] == 1) { @@ -635,10 +635,10 @@ int main() { printf("Student %d: Absent\n", student); } } - + return 0; } -```cpp +``` **Key Concepts:** - [ ] Fixed iteration for known number of students @@ -660,9 +660,9 @@ int main() { int item_count = 0; int is_running = 1; int choice; - + printf("=== Inventory Management System ===\n"); - + while (is_running) { printf("\n1. Add Item\n"); printf("2. Update Quantity\n"); @@ -671,18 +671,18 @@ int main() { printf("5. Exit\n"); printf("Choose option (1-5): "); scanf("%d", &choice); - + switch (choice) { case 1: { if (item_count < 50) { char new_item_name[50]; int new_quantity; - + printf("Enter item name: "); scanf("%s", new_item_name); printf("Enter initial quantity: "); scanf("%d", &new_quantity); - + if (new_quantity >= 0) { strcpy(item_names[item_count], new_item_name); item_quantities[item_count] = new_quantity; @@ -701,7 +701,7 @@ int main() { char search_name[50]; printf("Enter item name to update: "); scanf("%s", search_name); - + int found = 0; for (int i = 0; i < item_count; i++) { if (strcmp(item_names[i], search_name) == 0) { @@ -709,7 +709,7 @@ int main() { printf("Enter new quantity: "); int new_quantity; scanf("%d", &new_quantity); - + if (new_quantity >= 0) { item_quantities[i] = new_quantity; printf(" Quantity updated!\n"); @@ -720,7 +720,7 @@ int main() { break; } } - + if (!found) { printf(" Item not found!\n"); } @@ -743,14 +743,14 @@ int main() { if (item_count > 0) { printf("=== Low Stock Alert (≤5 units) ===\n"); int low_stock_count = 0; - + for (int i = 0; i < item_count; i++) { if (item_quantities[i] <= 5) { printf("%s: %d units \n", item_names[i], item_quantities[i]); low_stock_count++; } } - + if (low_stock_count == 0) { printf(" All items have sufficient stock.\n"); } @@ -766,12 +766,12 @@ int main() { break; } } - + printf("Thank you for using Inventory Management System! \n"); - + return 0; } -```cpp +``` **Key Concepts:** - [ ] 2D array for string storage @@ -789,48 +789,48 @@ int main() { int main() { int num_students, num_assignments; - + printf("=== Grade Book Calculator ===\n"); printf("Enter number of students: "); scanf("%d", &num_students); printf("Enter number of assignments: "); scanf("%d", &num_assignments); - + char student_names[50][50]; // Max 50 students, names up to 50 chars float grades[50][20]; // Max 50 students, 20 assignments - + // Input student data for (int student = 0; student < num_students; student++) { printf("Enter name for student %d: ", student + 1); scanf("%s", student_names[student]); - + float student_total = 0.0; for (int assignment = 0; assignment < num_assignments; assignment++) { - printf("Enter grade for %s assignment %d: ", + printf("Enter grade for %s assignment %d: ", student_names[student], assignment + 1); scanf("%f", &grades[student][assignment]); student_total += grades[student][assignment]; } - + float student_average = student_total / num_assignments; printf("%s's average: %.1f\n", student_names[student], student_average); } - + // Calculate class statistics printf("\n=== Class Statistics ===\n"); float class_total = 0.0; float highest_average = 0.0; float lowest_average = 100.0; - + for (int student = 0; student < num_students; student++) { float student_total = 0.0; for (int assignment = 0; assignment < num_assignments; assignment++) { student_total += grades[student][assignment]; } - + float student_average = student_total / num_assignments; class_total += student_average; - + if (student_average > highest_average) { highest_average = student_average; } @@ -838,40 +838,40 @@ int main() { lowest_average = student_average; } } - + float class_average = class_total / num_students; printf("Class average: %.1f\n", class_average); printf("Highest student average: %.1f\n", highest_average); printf("Lowest student average: %.1f\n", lowest_average); - + // Grade distribution printf("\n=== Grade Distribution ===\n"); int grade_ranges[5] = {0, 0, 0, 0, 0}; // A, B, C, D, F - + for (int student = 0; student < num_students; student++) { float student_total = 0.0; for (int assignment = 0; assignment < num_assignments; assignment++) { student_total += grades[student][assignment]; } - + float student_average = student_total / num_assignments; - + if (student_average >= 90) grade_ranges[0]++; else if (student_average >= 80) grade_ranges[1]++; else if (student_average >= 70) grade_ranges[2]++; else if (student_average >= 60) grade_ranges[3]++; else grade_ranges[4]++; } - + printf("A grades: %d\n", grade_ranges[0]); printf("B grades: %d\n", grade_ranges[1]); printf("C grades: %d\n", grade_ranges[2]); printf("D grades: %d\n", grade_ranges[3]); printf("F grades: %d\n", grade_ranges[4]); - + return 0; } -```cpp +``` **Key Concepts:** - [ ] 2D array processing with nested loops @@ -892,35 +892,35 @@ int main() { int main() { int password_length; char include_upper[10], include_numbers[10], include_special[10]; - + printf("=== Password Generator ===\n"); printf("Enter desired password length (8-20): "); scanf("%d", &password_length); - + while (password_length < 8 || password_length > 20) { printf(" Length must be between 8-20 characters!\n"); printf("Enter desired password length (8-20): "); scanf("%d", &password_length); } - + printf("Include uppercase letters? (y/n): "); scanf("%s", include_upper); printf("Include numbers? (y/n): "); scanf("%s", include_numbers); printf("Include special characters? (y/n): "); scanf("%s", include_special); - + // Character sets char lowercase[] = "abcdefghijklmnopqrstuvwxyz"; char uppercase[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; char numbers[] = "0123456789"; char special[] = "!@#$%^&*()_+-=[]{}|;:,.<>?"; - + // Build available character sets char* char_sets[10]; int set_count = 1; char_sets[0] = lowercase; // Always include lowercase - + if (strcmp(include_upper, "y") == 0 || strcmp(include_upper, "Y") == 0) { char_sets[set_count++] = uppercase; } @@ -930,23 +930,23 @@ int main() { if (strcmp(include_special, "y") == 0 || strcmp(include_special, "Y") == 0) { char_sets[set_count++] = special; } - + // Seed random number generator srand(time(NULL)); - + // Generate password char password[21]; // Max length 20 + null terminator for (int i = 0; i < password_length; i++) { // Pick random character set int set_index = rand() % set_count; char* selected_set = char_sets[set_index]; - + // Pick random character from set int char_index = rand() % strlen(selected_set); password[i] = selected_set[char_index]; } password[password_length] = '\0'; // Null terminate - + printf("Generated Password: %s\n", password); printf("Password length: %d\n", password_length); printf("Character sets used:\n"); @@ -960,10 +960,10 @@ int main() { printf(" Special characters\n"); } printf(" Lowercase letters (always included)\n"); - + return 0; } -```cpp +``` **Key Concepts:** - [ ] Input validation loop @@ -985,9 +985,9 @@ int main() { int total_votes = 0; int voting_active = 1; int choice; - + printf("=== Election Voting System ===\n"); - + while (voting_active) { printf("\n=== Vote Menu ===\n"); printf("Candidates:\n"); @@ -998,7 +998,7 @@ int main() { printf("5. End Voting\n"); printf("Enter your choice (1-5): "); scanf("%d", &choice); - + if (choice >= 1 && choice <= 3) { votes[choice - 1]++; total_votes++; @@ -1006,11 +1006,11 @@ int main() { } else if (choice == 4) { printf("=== Current Results ===\n"); printf("Total votes: %d\n", total_votes); - + if (total_votes > 0) { for (int i = 0; i < 3; i++) { float percentage = (float)votes[i] / total_votes * 100; - printf("%s: %d votes (%.1f%%)\n", + printf("%s: %d votes (%.1f%%)\n", candidate_names[i], votes[i], percentage); } } else { @@ -1022,37 +1022,37 @@ int main() { printf(" Invalid choice!\n"); } } - + if (total_votes > 0) { printf("\n=== Final Election Results ===\n"); - + // Find winner int winner_index = 0; int max_votes = votes[0]; - + for (int i = 1; i < 3; i++) { if (votes[i] > max_votes) { max_votes = votes[i]; winner_index = i; } } - - printf(" Winner: %s with %d votes!\n", + + printf(" Winner: %s with %d votes!\n", candidate_names[winner_index], max_votes); printf("Total votes cast: %d\n", total_votes); - + for (int i = 0; i < 3; i++) { float percentage = (float)votes[i] / total_votes * 100; - printf("%s: %d votes (%.1f%%)\n", + printf("%s: %d votes (%.1f%%)\n", candidate_names[i], votes[i], percentage); } } else { printf("No votes were cast.\n"); } - + return 0; } -```cpp +``` **Key Concepts:** - [ ] Menu-driven voting interface @@ -1079,7 +1079,7 @@ for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) { if (array[i] > max) max = array[i]; } -```cpp +``` **Early Termination:** ```c @@ -1090,11 +1090,11 @@ for (int i = 0; i < size; i++) { break; // Don't continue searching } } -```cpp +``` --- - **Fantastic! You've mastered loop-based algorithms!** + **Fantastic! You've mastered loop-based algorithms!** *Loops are the engines of computation. Next: Function pseudocode for modular programming! * @@ -1120,50 +1120,3 @@ Key functions and their purpose: - [ ] Main function: Entry point - [ ] Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```cpp -#include - -int main() { - printf("Hello, World!\n"); - return 0; -} -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard C++ conventions with proper imports and main function -2. **Output**: Uses printf to print messages to the console -3. **Standard Library**: Includes stdio.h for input/output operations -4. **Return Value**: Returns 0 to indicate successful execution -5. **Best Practices**: Code is readable and uses C++ idioms - -### Testing Your Solution - -1. **Compile**: `gcc main.c -o main` -2. **Run**: `./hello` -3. **Expected Output**: `Hello, World!` - -### Common Errors & Solutions - -| Error | Cause | Solution | -|-------|-------|----------| -| `command not found: gcc` | Compiler not installed | `sudo apt install gcc` (Ubuntu) | -| `undefined reference to main` | Missing main function | Ensure `int main()` exists | -| `error: implicit declaration of function 'printf'` | Missing stdio.h | Add `#include ` | - -### Tips for Learning - -- C uses stdio.h for input/output with additional features -- `printf` is the C standard for formatted output -- `\n` adds a newline character in format strings -- Format specifiers control how data is displayed (%d, %f, %s, etc.) diff --git a/lessons/c-c++/stage-2/level-7/lesson.md b/lessons/c-c++/stage-2/level-7/lesson.md index ea55e83..0c8c46b 100644 --- a/lessons/c-c++/stage-2/level-7/lesson.md +++ b/lessons/c-c++/stage-2/level-7/lesson.md @@ -48,7 +48,7 @@ Functions are the building blocks of organized code! Today you'll master algorit ## Algorithm 1: Calculator Program with Functions **Pseudocode:** -```cpp +``` Algorithm: Modular Calculator Program Function: display_menu() @@ -110,7 +110,7 @@ Main Algorithm: e. Else: i. Display " Invalid choice!" 3. Display "Thank you for using the calculator! " -```cpp +``` **Function Design:** - [ ] `display_menu()`: Handles UI display @@ -125,7 +125,7 @@ Main Algorithm: ## Algorithm 2: Student Grade Management System **Pseudocode:** -```cpp +``` Algorithm: Student Grade Management with Functions Function: display_main_menu() @@ -215,7 +215,7 @@ Main Algorithm: h. Else: i. Display " Invalid choice!" 6. Display "Thank you for using Grade Management System! " -```cpp +``` **Function Design:** - [ ] `display_main_menu()`: UI function @@ -231,7 +231,7 @@ Main Algorithm: ## Algorithm 3: Library Book System **Pseudocode:** -```cpp +``` Algorithm: Library Management System with Functions Function: display_library_menu() @@ -335,7 +335,7 @@ Main Algorithm: i. Else: i. Display " Invalid choice!" 7. Display "Thank you for using Library Management System! " -```cpp +``` **Function Design:** - [ ] `display_library_menu()`: UI function @@ -351,7 +351,7 @@ Main Algorithm: ## Algorithm 4: Math Quiz Game **Pseudocode:** -```cpp +``` Algorithm: Interactive Math Quiz with Functions Function: generate_question() @@ -421,7 +421,7 @@ Main Algorithm: g. Display blank line 7. Call display_score(correct_count, num_questions) 8. Display "Thanks for playing! " -```cpp +``` **Function Design:** - [ ] `generate_question()`: Random question creation @@ -438,7 +438,7 @@ Main Algorithm: ## Algorithm 5: Bank Account Manager **Pseudocode:** -```cpp +``` Algorithm: Bank Account Management with Functions Function: display_account_menu() @@ -525,7 +525,7 @@ Main Algorithm: h. Else: i. Display " Invalid choice!" 8. Display "Thank you for banking with us! " -```cpp +``` **Function Design:** - [ ] `display_account_menu()`: UI function @@ -541,7 +541,7 @@ Main Algorithm: ## Algorithm 6: Text Analyzer **Pseudocode:** -```cpp +``` Algorithm: Text Analysis Tool with Functions Function: count_words(text) @@ -604,7 +604,7 @@ Function: display_analysis(text) Set avg_word_length = calculate_average_word_length(text, word_count) Call find_most_frequent_character(text) Get most_frequent and freq_count from result - + Display "=== Text Analysis Results ===" Display "Characters: " + char_count Display "Words: " + word_count @@ -621,7 +621,7 @@ Main Algorithm: 5. Else: a. Display " No text entered." 6. Display "Analysis complete! " -```cpp +``` **Function Design:** - [ ] `count_words()`: Word counting logic @@ -648,7 +648,7 @@ int validate_user_input(char* input); int calc(float x); void process(); int check(char* str); -```cpp +``` **Parameter Design:** ```c @@ -657,7 +657,7 @@ void transfer_money(Account* from, Account* to, float amount); // Bad - unclear what parameters do void process(float a, float b, int c); -```cpp +``` **Return Value Design:** ```c @@ -666,7 +666,7 @@ int save_file(const char* filename); // Returns 0 on success, -1 on error // Bad - unclear return meaning int do_something(); -```cpp +``` --- @@ -700,13 +700,13 @@ int do_something(); ## Function Architecture Patterns ### Layered Architecture -```cpp +``` Presentation Layer (UI functions) ↓ Business Logic Layer (processing functions) ↓ Data Access Layer (storage/retrieval functions) -```cpp +``` ### Pipeline Pattern ```c @@ -718,7 +718,7 @@ Result process_data(Input data) { data = format_output(data); return data; } -```cpp +``` ### Factory Pattern ```c @@ -730,7 +730,7 @@ Calculator* create_calculator(CalculationType type) { default: return NULL; } } -```cpp +``` --- @@ -788,17 +788,17 @@ void display_result(const char* operation, float a, float b, float result) { int main() { int running = 1; - + while (running) { display_menu(); int choice; scanf("%d", &choice); - + if (choice >= 1 && choice <= 4) { float num1 = get_number("Enter first number: "); float num2 = get_number("Enter second number: "); float result; - + switch (choice) { case 1: result = perform_addition(num1, num2); @@ -825,11 +825,11 @@ int main() { printf(" Invalid choice!\n"); } } - + printf("Thank you for using the calculator! \n"); return 0; } -```cpp +``` **Key Concepts:** - [ ] Modular function design with single responsibilities @@ -859,12 +859,12 @@ int add_student(char students[50][50], float grades[50], int* count) { if (*count < 50) { char name[50]; float grade; - + printf("Enter student name: "); scanf("%s", name); printf("Enter grade (0-100): "); scanf("%f", &grade); - + if (grade >= 0 && grade <= 100) { strcpy(students[*count], name); grades[*count] = grade; @@ -903,12 +903,12 @@ float calculate_class_average(float grades[50], int count) { return 0; } -void find_top_performer(char students[50][50], float grades[50], int count, +void find_top_performer(char students[50][50], float grades[50], int count, char* top_student, float* max_grade) { if (count > 0) { *max_grade = grades[0]; strcpy(top_student, students[0]); - + for (int i = 1; i < count; i++) { if (grades[i] > *max_grade) { *max_grade = grades[i]; @@ -926,12 +926,12 @@ int main() { float grades[50]; int student_count = 0; int running = 1; - + while (running) { display_main_menu(); int choice; scanf("%d", &choice); - + switch (choice) { case 1: add_student(students, grades, &student_count); @@ -952,7 +952,7 @@ int main() { char top_student[50]; float max_grade; find_top_performer(students, grades, student_count, top_student, &max_grade); - + if (strcmp(top_student, "No students") != 0) { printf(" Top Performer: %s (%.1f%%)\n", top_student, max_grade); } else { @@ -968,11 +968,11 @@ int main() { break; } } - + printf("Thank you for using Grade Management System! \n"); return 0; } -```cpp +``` **Key Concepts:** - [ ] Array parameters with pointers for modification @@ -1002,21 +1002,21 @@ void display_library_menu() { int add_book(char titles[100][100], char authors[100][50], int available[100], int* count) { if (*count < 100) { char title[100], author[50]; - + printf("Enter book title: "); getchar(); // Clear newline fgets(title, sizeof(title), stdin); title[strcspn(title, "\n")] = '\0'; // Remove newline - + printf("Enter author name: "); fgets(author, sizeof(author), stdin); author[strcspn(author, "\n")] = '\0'; - + strcpy(titles[*count], title); strcpy(authors[*count], author); available[*count] = 1; // true (*count)++; - + printf(" Book added successfully!\n"); return 1; } else { @@ -1025,11 +1025,11 @@ int add_book(char titles[100][100], char authors[100][50], int available[100], i } } -int search_books(char titles[100][100], char authors[100][50], int available[100], +int search_books(char titles[100][100], char authors[100][50], int available[100], int count, const char* search_term) { int found_count = 0; printf("=== Search Results for '%s' ===\n", search_term); - + for (int i = 0; i < count; i++) { if (strstr(titles[i], search_term) != NULL || strstr(authors[i], search_term) != NULL) { printf(" %s by %s\n", titles[i], authors[i]); @@ -1037,11 +1037,11 @@ int search_books(char titles[100][100], char authors[100][50], int available[100 found_count++; } } - + if (found_count == 0) { printf(" No books found matching '%s'\n", search_term); } - + return found_count; } @@ -1087,12 +1087,12 @@ int main() { int available[100]; int book_count = 0; int running = 1; - + while (running) { display_library_menu(); int choice; scanf("%d", &choice); - + switch (choice) { case 1: add_book(titles, authors, available, &book_count); @@ -1135,11 +1135,11 @@ int main() { break; } } - + printf("Thank you for using Library Management System! \n"); return 0; } -```cpp +``` **Key Concepts:** - [ ] Complex string handling with fgets and newline removal @@ -1158,10 +1158,10 @@ int main() { void generate_question(int* num1, char* operation, int* num2) { *operation = "+-*/"[rand() % 4]; // Random operation - + *num1 = rand() % 20 + 1; *num2 = rand() % 20 + 1; - + // Ensure clean division if (*operation == '/') { *num1 = *num2 * (rand() % 10 + 1); @@ -1202,10 +1202,10 @@ int check_answer(int user_answer, int correct_answer) { void display_score(int correct_answers, int total_questions) { float percentage = (float)correct_answers / total_questions * 100; - + printf("=== Quiz Complete ===\n"); printf("Score: %d/%d (%.1f%%)\n", correct_answers, total_questions, percentage); - + if (percentage >= 90) { printf(" Excellent! Math Master!\n"); } else if (percentage >= 70) { @@ -1219,42 +1219,42 @@ void display_score(int correct_answers, int total_questions) { int main() { srand(time(NULL)); // Seed random number generator - + printf("=== Math Quiz Game ===\n"); printf("How many questions? (1-20): "); int num_questions; scanf("%d", &num_questions); - + while (num_questions < 1 || num_questions > 20) { printf(" Please enter 1-20 questions.\n"); scanf("%d", &num_questions); } - + int correct_count = 0; - + for (int question_num = 1; question_num <= num_questions; question_num++) { int num1, num2; char operation; - + generate_question(&num1, &operation, &num2); display_question(num1, operation, num2, question_num); - + int correct_answer = calculate_answer(num1, operation, num2); int user_answer = get_user_answer(); - + if (check_answer(user_answer, correct_answer)) { correct_count++; } - + printf("\n"); } - + display_score(correct_count, num_questions); printf("Thanks for playing! \n"); - + return 0; } -```cpp +``` **Key Concepts:** - [ ] Random number generation for question creation @@ -1311,8 +1311,8 @@ float withdraw_money(float balance, float amount) { } } -int add_transaction(char transactions[100][20], float amounts[100], - char descriptions[100][30], int* count, float amount, +int add_transaction(char transactions[100][20], float amounts[100], + char descriptions[100][30], int* count, float amount, const char* description) { if (*count < 100) { // Simplified transaction recording @@ -1327,7 +1327,7 @@ int add_transaction(char transactions[100][20], float amounts[100], } } -void display_transaction_history(char transactions[100][20], float amounts[100], +void display_transaction_history(char transactions[100][20], float amounts[100], char descriptions[100][30], int count) { if (count > 0) { printf("=== Transaction History ===\n"); @@ -1346,12 +1346,12 @@ int main() { char descriptions[100][30]; int transaction_count = 0; int running = 1; - + while (running) { display_account_menu(); int choice; scanf("%d", &choice); - + switch (choice) { case 1: display_balance(balance); @@ -1363,7 +1363,7 @@ int main() { float old_balance = balance; balance = deposit_money(balance, amount); if (amount > 0) { - add_transaction(transactions, amounts, descriptions, + add_transaction(transactions, amounts, descriptions, &transaction_count, amount, "Deposit"); } break; @@ -1375,7 +1375,7 @@ int main() { float old_balance = balance; balance = withdraw_money(balance, amount); if (amount > 0 && amount <= old_balance) { - add_transaction(transactions, amounts, descriptions, + add_transaction(transactions, amounts, descriptions, &transaction_count, -amount, "Withdrawal"); } break; @@ -1391,11 +1391,11 @@ int main() { break; } } - + printf("Thank you for banking with us! \n"); return 0; } -```cpp +``` **Key Concepts:** - [ ] Financial transaction processing @@ -1415,7 +1415,7 @@ int main() { int count_words(const char* text) { int word_count = 0; int in_word = 0; - + for (int i = 0; text[i] != '\0'; i++) { if (isalpha(text[i]) && !in_word) { in_word = 1; @@ -1424,19 +1424,19 @@ int count_words(const char* text) { in_word = 0; } } - + return word_count; } int count_sentences(const char* text) { int sentence_count = 0; - + for (int i = 0; text[i] != '\0'; i++) { if (text[i] == '.' || text[i] == '!' || text[i] == '?') { sentence_count++; } } - + return sentence_count; } @@ -1446,11 +1446,11 @@ int count_characters(const char* text) { float calculate_average_word_length(const char* text, int word_count) { if (word_count == 0) return 0.0; - + int total_length = 0; int current_word_length = 0; int in_word = 0; - + for (int i = 0; text[i] != '\0'; i++) { if (isalpha(text[i])) { in_word = 1; @@ -1461,34 +1461,34 @@ float calculate_average_word_length(const char* text, int word_count) { in_word = 0; } } - + // Handle last word if (in_word) { total_length += current_word_length; } - + return (float)total_length / word_count; } void find_most_frequent_character(const char* text, char* most_frequent, int* freq_count) { int char_counts[256] = {0}; - + for (int i = 0; text[i] != '\0'; i++) { if (text[i] != ' ') { char_counts[(unsigned char)text[i]]++; } } - + int max_count = 0; char most_freq = ' '; - + for (int i = 0; i < 256; i++) { if (char_counts[i] > max_count) { max_count = char_counts[i]; most_freq = (char)i; } } - + *most_frequent = most_freq; *freq_count = max_count; } @@ -1498,11 +1498,11 @@ void display_analysis(const char* text) { int sentence_count = count_sentences(text); int char_count = count_characters(text); float avg_word_length = calculate_average_word_length(text, word_count); - + char most_frequent; int freq_count; find_most_frequent_character(text, &most_frequent, &freq_count); - + printf("=== Text Analysis Results ===\n"); printf("Characters: %d\n", char_count); printf("Words: %d\n", word_count); @@ -1514,23 +1514,23 @@ void display_analysis(const char* text) { int main() { printf("=== Text Analyzer ===\n"); printf("Enter text to analyze (max 1000 characters):\n"); - + char text[1001]; fgets(text, sizeof(text), stdin); - + // Remove trailing newline text[strcspn(text, "\n")] = '\0'; - + if (strlen(text) > 0) { display_analysis(text); } else { printf(" No text entered.\n"); } - + printf("Analysis complete! \n"); return 0; } -```cpp +``` **Key Concepts:** - [ ] Text processing algorithms @@ -1560,7 +1560,7 @@ int main() { --- - **Congratulations! You've mastered function-based programming!** + **Congratulations! You've mastered function-based programming!** *Functions are the cornerstone of good software design. Next: Stage 3 - Problem to Pseudocode! * @@ -1586,50 +1586,3 @@ Key functions and their purpose: - [ ] Main function: Entry point - [ ] Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```cpp -#include - -int main() { - printf("Hello, World!\n"); - return 0; -} -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard C++ conventions with proper imports and main function -2. **Output**: Uses printf to print messages to the console -3. **Standard Library**: Includes stdio.h for input/output operations -4. **Return Value**: Returns 0 to indicate successful execution -5. **Best Practices**: Code is readable and uses C++ idioms - -### Testing Your Solution - -1. **Compile**: `gcc main.c -o main` -2. **Run**: `./hello` -3. **Expected Output**: `Hello, World!` - -### Common Errors & Solutions - -| Error | Cause | Solution | -|-------|-------|----------| -| `command not found: gcc` | Compiler not installed | `sudo apt install gcc` (Ubuntu) | -| `undefined reference to main` | Missing main function | Ensure `int main()` exists | -| `error: implicit declaration of function 'printf'` | Missing stdio.h | Add `#include ` | - -### Tips for Learning - -- C++ is a superset of C with additional features -- `printf` is the C standard for formatted output -- `\n` adds a newline character in format strings -- Format specifiers control how data is displayed (%d, %f, %s, etc.) diff --git a/lessons/c-c++/stage-3/level-1/lesson.md b/lessons/c-c++/stage-3/level-1/lesson.md index 035afce..46fab74 100644 --- a/lessons/c-c++/stage-3/level-1/lesson.md +++ b/lessons/c-c++/stage-3/level-1/lesson.md @@ -80,10 +80,10 @@ Create a program that asks the user for a temperature in Fahrenheit and classifi The program should display both the temperature and its classification. **Example:** -```cpp +``` Enter temperature in Fahrenheit: 75 Temperature: 75°F - Comfortable -```cpp +``` **Your Task:** 1. Write pseudocode for this problem @@ -103,13 +103,13 @@ Create a program that simulates a vending machine selling snacks for $1.50 each. - [ ] Handle cases where payment is insufficient **Example:** -```cpp +``` How many snacks would you like? 3 Total cost: $4.50 Enter payment amount: $5.00 Change: $0.50 Thank you for your purchase! -```cpp +``` **Your Task:** 1. Write pseudocode for this vending machine @@ -131,11 +131,11 @@ Create a program that asks for a person's age and determines their life stage ca Also display how many years until the next category (or "Final stage" if Senior). **Example:** -```cpp +``` Enter age: 25 Category: Young Adult Years until next category: 11 -```cpp +``` **Your Task:** 1. Write pseudocode for age categorization @@ -157,7 +157,7 @@ Create a program that calculates movie ticket prices based on: The program should ask for age, show time (24-hour format), and number of tickets. **Example:** -```cpp +``` Enter age: 70 Enter show time (0-23): 14 Enter number of tickets: 2 @@ -167,7 +167,7 @@ Senior discount: 30% off Matinee discount: 20% off Final price per ticket: $6.72 Total for 2 tickets: $13.44 -```cpp +``` **Your Task:** 1. Write pseudocode for ticket price calculation @@ -187,14 +187,14 @@ Create a program that asks the user for three numbers and: - [ ] Determines if the numbers form an increasing sequence **Example:** -```cpp +``` Enter three numbers: 5 8 3 Largest: 8 Smallest: 3 Average: 5.33 All equal: No Increasing sequence: No -```cpp +``` **Your Task:** 1. Write pseudocode for number analysis @@ -216,11 +216,11 @@ Create a program that converts a numerical grade (0-100) to a letter grade: Also display a motivational message based on the grade. **Example:** -```cpp +``` Enter numerical grade (0-100): 87 Letter grade: B Message: Good job! Keep up the excellent work! -```cpp +``` **Your Task:** 1. Write pseudocode for grade conversion @@ -232,17 +232,17 @@ Message: Good job! Keep up the excellent work! ### Pseudocode Writing Guidelines **Good Pseudocode Structure:** -```cpp +``` Algorithm: Problem Name 1. Clear step-by-step instructions 2. Handle all input/output 3. Include decision points 4. Handle edge cases 5. End with clear output -```cpp +``` **Example:** -```cpp +``` Algorithm: Temperature Classifier 1. Display "Enter temperature in Fahrenheit: " 2. Get temperature from user @@ -256,7 +256,7 @@ Algorithm: Temperature Classifier a. Display temperature + "°F - Warm" 7. Else: a. Display temperature + "°F - Hot" -```cpp +``` --- @@ -327,7 +327,7 @@ Algorithm: Temperature Classifier - [ ] Edge cases: Negative temperatures, very high temperatures **Sample Pseudocode:** -```cpp +``` Algorithm: Temperature Classifier 1. Display "Enter temperature in Fahrenheit: " 2. Get temperature from user @@ -341,7 +341,7 @@ Algorithm: Temperature Classifier a. Display temperature + "°F - Warm" 7. Else: a. Display temperature + "°F - Hot" -```cpp +``` **Test Cases:** - [ ] 25°F → Freezing @@ -361,7 +361,7 @@ Algorithm: Temperature Classifier - [ ] Constants: Snack price = $1.50 **Sample Pseudocode:** -```cpp +``` Algorithm: Vending Machine 1. Set snack_price to 1.50 2. Display "How many snacks would you like? " @@ -377,7 +377,7 @@ Algorithm: Vending Machine 9. Else: a. Calculate needed = total_cost - payment b. Display "Insufficient payment. You need $" + needed + " more." -```cpp +``` --- @@ -447,23 +447,23 @@ Algorithm: Vending Machine ### Common Problem-Solving Patterns **Range Checking:** -```cpp +``` If value >= min AND value <= max: Process valid value Else: Handle invalid value -```cpp +``` **Sequential Processing:** -```cpp +``` Step 1: Get input Step 2: Validate input Step 3: Process data Step 4: Display results -```cpp +``` **Decision Trees:** -```cpp +``` If condition A: If sub-condition A1: Action A1 @@ -473,7 +473,7 @@ Else if condition B: Action B Else: Default action -```cpp +``` --- @@ -497,7 +497,7 @@ Else: --- - **Congratulations! You've created your first independent algorithms!** + **Congratulations! You've created your first independent algorithms!** *Problem analysis is the foundation of programming. Next: Data management problems! * @@ -539,7 +539,7 @@ Expected implementation provided. ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/stage-3/level-2/lesson.md b/lessons/c-c++/stage-3/level-2/lesson.md index 88848f4..f60e097 100644 --- a/lessons/c-c++/stage-3/level-2/lesson.md +++ b/lessons/c-c++/stage-3/level-2/lesson.md @@ -66,7 +66,7 @@ Create a program that manages student grades for a class. The program should: - [ ] Search/filter capabilities **Example Usage:** -```cpp +``` 1. Add Student 2. View All Students 3. Show Statistics @@ -83,7 +83,7 @@ Class Statistics: Average: 87.5% Highest: 95% (Alice) Lowest: 80% (Bob) -```cpp +``` **Your Task:** 1. Design data structures for student information @@ -110,7 +110,7 @@ Create an inventory management system for a small store with: - [ ] Search functionality **Example Usage:** -```cpp +``` Inventory System: 1. Add Product 2. Update Stock @@ -129,7 +129,7 @@ Choice: 4 Low Stock Alert: - [ ] Mouse: 3 units remaining - [ ] Keyboard: 2 units remaining -```cpp +``` **Your Task:** 1. Design product data structure @@ -158,7 +158,7 @@ Build a digital address book that can: - [ ] Contact management operations **Example Usage:** -```cpp +``` Contact Manager: 1. Add Contact 2. Search Contact @@ -175,7 +175,7 @@ Contact added! Choice: 2 Enter search name: John Found: John Doe - (555) 123-4567 - john@example.com -```cpp +``` **Your Task:** 1. Design contact data structure @@ -203,7 +203,7 @@ Create a library system that tracks: - [ ] Statistical reporting **Example Usage:** -```cpp +``` Library System: 1. Add Book 2. Search Books @@ -218,7 +218,7 @@ Total Books: 150 Available: 120 Checked Out: 30 Most Popular Author: J.K. Rowling (8 books) -```cpp +``` **Your Task:** 1. Design book database structure @@ -247,7 +247,7 @@ Build a personal finance tracker that: - [ ] Financial calculations and summaries **Example Usage:** -```cpp +``` Expense Tracker: 1. Add Expense 2. View by Category @@ -263,7 +263,7 @@ Entertainment: $89.99 Utilities: $200.00 Other: $50.25 Total: $910.74 -```cpp +``` **Your Task:** 1. Design expense data structure @@ -292,7 +292,7 @@ Create a to-do list manager that can: - [ ] Search and filter capabilities **Example Usage:** -```cpp +``` Task Manager: 1. Add Task 2. Complete Task @@ -309,7 +309,7 @@ High Priority Tasks: Medium Priority Tasks: 1. Buy groceries (Completed) 2. Clean room (Not completed) -```cpp +``` **Your Task:** 1. Design task data structure @@ -334,7 +334,7 @@ Medium Priority Tasks: - [ ] **Consider access patterns** (how data will be used) **Example Design:** -```cpp +``` Student Grade Book: - [ ] student_names[100][50] - array of strings - [ ] student_grades[100] - array of floats @@ -342,7 +342,7 @@ Student Grade Book: Each student[i] corresponds to: - [ ] student_names[i] and student_grades[i] -```cpp +``` --- @@ -380,7 +380,7 @@ Each student[i] corresponds to: ## Data Management Patterns ### Array Management -```cpp +``` Initialize array and counter While adding items: If not at capacity: @@ -388,10 +388,10 @@ While adding items: Increment counter Else: Show capacity error -```cpp +``` ### Search Operations -```cpp +``` Initialize found flag to false For each item in collection: If item matches search criteria: @@ -399,19 +399,19 @@ For each item in collection: Set found flag to true If not found: Display "not found" message -```cpp +``` ### Data Validation -```cpp +``` When receiving input: Check if input is valid format Check if input is within acceptable range Check for required fields Show appropriate error messages -```cpp +``` ### Statistical Calculations -```cpp +``` Initialize accumulator variables For each data item: Add to running totals @@ -419,7 +419,7 @@ For each data item: Count valid items Calculate averages and percentages Display formatted results -```cpp +``` --- @@ -432,11 +432,11 @@ Display formatted results ### Problem 1: Student Grade Book **Data Structure Design:** -```cpp +``` student_names[25][50] - array of student names student_grades[25] - array of corresponding grades student_count - number of students currently stored -```cpp +``` **Key Operations:** - [ ] Add student: Validate grade range, store in next available slot @@ -455,12 +455,12 @@ student_count - number of students currently stored ### Problem 2: Inventory Tracker **Data Structure Design:** -```cpp +``` product_names[50][50] - product names product_prices[50] - product prices product_stock[50] - current stock levels product_count - number of products -```cpp +``` **Key Operations:** - [ ] Add product: Store name, price, initial stock @@ -479,12 +479,12 @@ product_count - number of products ### Problem 3: Contact List Manager **Data Structure Design:** -```cpp +``` contact_names[100][50] - contact names contact_phones[100][20] - phone numbers contact_emails[100][50] - email addresses contact_count - number of contacts -```cpp +``` **Key Operations:** - [ ] Add contact: Validate phone/email format, store all fields @@ -502,13 +502,13 @@ contact_count - number of contacts ### Problem 4: Library Book Database **Data Structure Design:** -```cpp +``` book_titles[200][100] - book titles book_authors[200][50] - author names book_isbns[200][20] - ISBN numbers book_available[200] - availability status (1=available, 0=checked out) book_count - number of books -```cpp +``` **Key Operations:** - [ ] Add book: Store all book information @@ -526,13 +526,13 @@ book_count - number of books ### Problem 5: Expense Tracker **Data Structure Design:** -```cpp +``` expense_dates[100][20] - expense dates (MM/DD/YYYY format) expense_descriptions[100][100] - expense descriptions expense_amounts[100] - expense amounts expense_categories[100] - category indices (0=Food, 1=Transportation, etc.) expense_count - number of expenses -```cpp +``` **Key Operations:** - [ ] Add expense: Store all expense details @@ -541,22 +541,22 @@ expense_count - number of expenses - [ ] Budget alerts: Compare against monthly budgets **Categories Array:** -```cpp +``` categories[5] = {"Food", "Transportation", "Entertainment", "Utilities", "Other"} -```cpp +``` --- ### Problem 6: Task Management System **Data Structure Design:** -```cpp +``` task_titles[50][100] - task titles task_descriptions[50][200] - task descriptions task_priorities[50] - priority levels (0=Low, 1=Medium, 2=High) task_completed[50] - completion status (0=pending, 1=completed) task_count - number of tasks -```cpp +``` **Key Operations:** - [ ] Add task: Store all task information @@ -566,12 +566,12 @@ task_count - number of tasks - [ ] Statistics: Completion rates, priority distribution **Priority Display:** -```cpp +``` High Priority: Show first (most important) Medium Priority: Show second Low Priority: Show last Completed tasks: Show with checkmark -```cpp +``` --- @@ -583,7 +583,7 @@ Completed tasks: Show with checkmark char names[MAX_ITEMS][50]; float values[MAX_ITEMS]; int count = 0; -```cpp +``` **Add One Operation at a Time:** 1. Implement data storage @@ -600,7 +600,7 @@ int count = 0; --- - **Excellent! You're mastering data management and organization!** + **Excellent! You're mastering data management and organization!** *Data structures are the foundation of all software. Next: Mathematical problem solving! * @@ -642,7 +642,7 @@ Expected implementation provided. ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/stage-3/level-3/lesson.md b/lessons/c-c++/stage-3/level-3/lesson.md index 1613cdc..2450a30 100644 --- a/lessons/c-c++/stage-3/level-3/lesson.md +++ b/lessons/c-c++/stage-3/level-3/lesson.md @@ -80,10 +80,10 @@ Create a program that calculates the nth Fibonacci number. The Fibonacci sequenc The program should ask for n and display the nth Fibonacci number. **Example:** -```cpp +``` Enter n: 8 Fibonacci number 8 is: 21 -```cpp +``` **Your Task:** 1. Write pseudocode for Fibonacci calculation @@ -98,15 +98,13 @@ Fibonacci number 8 is: 21 Create a program that determines if a given number is prime. A prime number is a positive integer greater than 1 that has no positive divisors other than 1 and itself. **Example:** -```cpp +``` Enter a number: 17 17 is a prime number. -```cpp -```cpp Enter a number: 15 15 is not a prime number. -```cpp +``` **Your Task:** 1. Write pseudocode for primality testing @@ -124,10 +122,10 @@ Create a program that calculates the factorial of a given number. Factorial of n - [ ] n! = n × (n-1) × (n-2) × ... × 1 **Example:** -```cpp +``` Enter n: 5 5! = 120 -```cpp +``` **Your Task:** 1. Write pseudocode for factorial calculation @@ -150,7 +148,7 @@ Where: - [ ] t = time in years **Example:** -```cpp +``` Enter principal amount: 1000 Enter annual interest rate (decimal): 0.05 Enter compounding frequency per year: 12 @@ -158,7 +156,7 @@ Enter time in years: 2 Final amount: $1104.54 Interest earned: $104.54 -```cpp +``` **Your Task:** 1. Write pseudocode for compound interest calculation @@ -180,14 +178,14 @@ Where: - [ ] n = number of terms **Example:** -```cpp +``` Enter first term: 3 Enter common difference: 2 Enter number of terms: 5 Series: 3, 5, 7, 9, 11 Sum: 35 -```cpp +``` **Your Task:** 1. Write pseudocode for arithmetic series sum @@ -204,11 +202,11 @@ Create a program that determines if a number is perfect. A perfect number is a p Example: 6 is perfect because 1 + 2 + 3 = 6 **Example:** -```cpp +``` Enter a number: 28 28 is a perfect number. Divisors: 1, 2, 4, 7, 14 (sum = 28) -```cpp +``` **Your Task:** 1. Write pseudocode for perfect number checking @@ -220,24 +218,24 @@ Divisors: 1, 2, 4, 7, 14 (sum = 28) ### Mathematical Pseudocode Guidelines **Formula Implementation:** -```cpp +``` Algorithm: Formula Calculator 1. Identify all variables in the formula 2. Determine the order of operations 3. Handle special cases (division by zero, etc.) 4. Calculate step by step 5. Display results with appropriate precision -```cpp +``` **Sequence Generation:** -```cpp +``` Algorithm: Sequence Generator 1. Initialize first terms 2. Use loop to generate subsequent terms 3. Apply the sequence rule 4. Store or display terms as needed 5. Handle termination conditions -```cpp +``` --- @@ -306,7 +304,7 @@ Algorithm: Sequence Generator - [ ] Efficiency: Iterative approach for large n **Sample Pseudocode:** -```cpp +``` Algorithm: Fibonacci Calculator 1. Display "Enter n: " 2. Get n from user @@ -321,7 +319,7 @@ Algorithm: Fibonacci Calculator ii. Set a = b iii. Set b = temp c. Display "Fibonacci number " + n + " is: " + b -```cpp +``` --- @@ -423,7 +421,7 @@ Algorithm: Fibonacci Calculator --- - **Congratulations! You've mastered mathematical algorithms!** + **Congratulations! You've mastered mathematical algorithms!** *Next: Interactive problems with user interfaces and menus! * @@ -465,7 +463,7 @@ Expected implementation provided. ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/stage-3/level-4/lesson.md b/lessons/c-c++/stage-3/level-4/lesson.md index f0eb437..5a4cd6e 100644 --- a/lessons/c-c++/stage-3/level-4/lesson.md +++ b/lessons/c-c++/stage-3/level-4/lesson.md @@ -84,7 +84,7 @@ Create an interactive calculator program with a menu that allows users to: The program should display a menu, get user choice, perform the selected operation, and return to the menu until the user chooses to exit. **Example:** -```cpp +``` === Calculator Menu === 1. Addition 2. Subtraction @@ -98,7 +98,7 @@ Enter second number: 5 Result: 10 + 5 = 15 Press Enter to continue... -```cpp +``` **Your Task:** 1. Write pseudocode for menu-driven calculator @@ -120,7 +120,7 @@ Create a banking system menu that allows users to: Maintain a balance and track transactions. Handle insufficient funds for withdrawals. **Example:** -```cpp +``` === Banking Menu === 1. Check Balance 2. Deposit @@ -133,7 +133,7 @@ Enter deposit amount: 100 Deposit successful! New balance: $100.00 Press Enter to continue... -```cpp +``` **Your Task:** 1. Write pseudocode for banking system @@ -155,7 +155,7 @@ Create a student grade management system with menu options: Store up to 10 student names and grades. Handle cases where no grades are entered. **Example:** -```cpp +``` === Grade Manager === 1. Add Student Grade 2. View All Grades @@ -169,7 +169,7 @@ Enter grade (0-100): 95 Grade added successfully! Press Enter to continue... -```cpp +``` **Your Task:** 1. Write pseudocode for grade management @@ -192,7 +192,7 @@ Create a restaurant menu system with: Include at least 5 menu items with prices. Allow multiple items in one order. **Example:** -```cpp +``` === Restaurant Menu === 1. View Menu 2. Place Order @@ -210,7 +210,7 @@ Enter choice: 1 5. Dessert - $4.99 Press Enter to continue... -```cpp +``` **Your Task:** 1. Write pseudocode for restaurant ordering @@ -233,7 +233,7 @@ Create a library book management system with: Track book availability and borrower names. Handle cases where books are not available. **Example:** -```cpp +``` === Library System === 1. Add Book 2. Search Books @@ -248,7 +248,7 @@ Enter author: Kernighan & Ritchie Book added successfully! Press Enter to continue... -```cpp +``` **Your Task:** 1. Write pseudocode for library system @@ -270,7 +270,7 @@ Create a simple game menu system with: Include a number guessing game for "Start New Game". Track high scores and allow basic settings. **Example:** -```cpp +``` === Game Menu === 1. Start New Game 2. Load Game @@ -287,7 +287,7 @@ Too low! Try again: 37 Correct! You won in 3 guesses! Press Enter to continue... -```cpp +``` **Your Task:** 1. Write pseudocode for game menu system @@ -299,7 +299,7 @@ Press Enter to continue... ### Interactive Pseudocode Guidelines **Menu System Structure:** -```cpp +``` Algorithm: Menu System 1. Display menu options clearly 2. Get user choice @@ -307,10 +307,10 @@ Algorithm: Menu System 4. Process choice with appropriate action 5. Return to menu or exit based on choice 6. Handle invalid inputs gracefully -```cpp +``` **Input Validation Loop:** -```cpp +``` While input is invalid: Display prompt Get user input @@ -320,7 +320,7 @@ While input is invalid: Else: Display error message Continue loop -```cpp +``` --- @@ -390,7 +390,7 @@ While input is invalid: - [ ] Loop until user chooses exit **Menu Structure:** -```cpp +``` While user hasn't chosen exit: Display menu Get choice @@ -402,7 +402,7 @@ While user hasn't chosen exit: Exit program Else: Display invalid choice message -```cpp +``` --- @@ -507,7 +507,7 @@ While user hasn't chosen exit: --- - **Congratulations! You've created interactive user interfaces!** + **Congratulations! You've created interactive user interfaces!** *Next: Decision-based problems with rule engines and eligibility systems! * @@ -549,7 +549,7 @@ Expected implementation provided. ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/stage-3/level-5/lesson.md b/lessons/c-c++/stage-3/level-5/lesson.md index 4f3800d..cb0cc02 100644 --- a/lessons/c-c++/stage-3/level-5/lesson.md +++ b/lessons/c-c++/stage-3/level-5/lesson.md @@ -88,7 +88,7 @@ Eligibility rules: - [ ] Employed applicants get preferred rates **Example:** -```cpp +``` === Loan Application === Enter credit score (300-850): 720 Enter annual income: 45000 @@ -100,7 +100,7 @@ ELIGIBLE! Loan amount: $100,000 Interest rate: 6.5% Monthly payment: $632.07 -```cpp +``` **Your Task:** 1. Write pseudocode for loan eligibility rules @@ -120,7 +120,7 @@ Create an insurance premium calculator with rules: - [ ] Coverage level: Basic (+0%), Standard (+25%), Premium (+50%) **Example:** -```cpp +``` === Insurance Quote === Enter age: 28 Enter accidents in last 3 years: 0 @@ -129,7 +129,7 @@ Enter coverage level (basic/standard/premium): standard Annual Premium: $687.50 (Base: $500 + Age: $0 + Record: -$50 + Vehicle: $0 + Coverage: $125) -```cpp +``` **Your Task:** 1. Write pseudocode for premium calculation rules @@ -155,7 +155,7 @@ Award levels: - [ ] Honorable mention: GPA >=3.5 AND essay >=7 **Example:** -```cpp +``` === Scholarship Application === Enter GPA (0.0-4.0): 3.8 Enter family income: 35000 @@ -166,7 +166,7 @@ Enter recommendation score (1-10): 9 AWARD: Partial Scholarship Reason: Strong GPA and leadership experience -```cpp +``` **Your Task:** 1. Write pseudocode for scholarship rules @@ -188,7 +188,7 @@ Create a tax calculator for 2024 tax brackets: Also calculate effective tax rate and after-tax income. **Example:** -```cpp +``` === Tax Calculator === Enter annual income: 75000 @@ -201,7 +201,7 @@ Tax breakdown: 10% bracket: $1,100.00 12% bracket: $4,032.00 22% bracket: $3,715.50 -```cpp +``` **Your Task:** 1. Write pseudocode for tax bracket calculations @@ -224,7 +224,7 @@ Create a simple medical diagnosis assistant with symptoms: Provide diagnosis and recommend seeing a doctor if multiple symptoms match. **Example:** -```cpp +``` === Symptom Checker === Do you have a fever? (y/n): y Do you have a cough? (y/n): y @@ -234,7 +234,7 @@ Do you feel nauseous? (y/n): n Possible diagnosis: Flu Recommendation: Rest, drink fluids, see doctor if symptoms worsen -```cpp +``` **Your Task:** 1. Write pseudocode for diagnosis rules @@ -260,7 +260,7 @@ Screening rules: - [ ] Offer: Interview qualified AND salary match AND local **Example:** -```cpp +``` === Application Screening === Enter years of experience: 4 Enter education level (HS/Associate/BS/MS): BS @@ -271,7 +271,7 @@ Offered salary range: 80000-90000 SCREENING RESULT: Interview Reason: Good experience, education, and skills match -```cpp +``` **Your Task:** 1. Write pseudocode for screening rules @@ -283,7 +283,7 @@ Reason: Good experience, education, and skills match ### Decision Logic Guidelines **Rule Engine Structure:** -```cpp +``` Algorithm: Decision Engine 1. Gather all input criteria 2. Evaluate primary rules first @@ -291,17 +291,17 @@ Algorithm: Decision Engine 4. Apply rule combinations (AND/OR) 5. Determine final decision 6. Provide reasoning for decision -```cpp +``` **Complex Condition Handling:** -```cpp +``` If (condition_A AND condition_B) OR (condition_C AND condition_D): Outcome 1 Else if condition_E OR (condition_F AND condition_G): Outcome 2 Else: Default outcome -```cpp +``` --- @@ -371,7 +371,7 @@ Else: - [ ] Calculation of loan terms if eligible **Decision Tree:** -```cpp +``` If (credit >= 650 AND income >= 30000 AND dti < 40) OR (credit >= 700 AND income >= 25000): If loan_amount <= income * 3: ELIGIBLE @@ -380,7 +380,7 @@ If (credit >= 650 AND income >= 30000 AND dti < 40) OR (credit >= 700 AND income INELIGIBLE - Loan too large Else: INELIGIBLE - Doesn't meet criteria -```cpp +``` --- @@ -392,14 +392,14 @@ Else: - [ ] Percentage-based modifications **Calculation Structure:** -```cpp +``` base_premium = 500 age_adjustment = calculate_age_factor(age) record_adjustment = calculate_record_factor(accidents) vehicle_adjustment = calculate_vehicle_factor(type) coverage_adjustment = calculate_coverage_factor(level) total = base + age + record + vehicle + coverage -```cpp +``` --- @@ -411,7 +411,7 @@ total = base + age + record + vehicle + coverage - [ ] Priority ranking for awards **Evaluation Logic:** -```cpp +``` score = 0 If GPA >= 3.5: score += 1 If income < 50000: score += 1 @@ -423,7 +423,7 @@ If recommendation >= 8: score += 1 If score >= 5 AND GPA == 4.0: Full Scholarship Else if score >= 4: Partial Scholarship Else if score >= 3: Honorable Mention -```cpp +``` --- @@ -435,7 +435,7 @@ Else if score >= 3: Honorable Mention - [ ] Marginal vs effective rates **Tax Calculation:** -```cpp +``` taxable = income - deduction tax = 0 @@ -449,7 +449,7 @@ If taxable > 0: bracket2 = min(taxable, 33725) tax += bracket2 * 0.12 // Continue for other brackets -```cpp +``` --- @@ -461,7 +461,7 @@ If taxable > 0: - [ ] Multiple possible diagnoses **Diagnosis Logic:** -```cpp +``` flu_score = 0 if fever: flu_score += 1 if cough or fatigue: flu_score += 1 @@ -473,7 +473,7 @@ if headache: cold_score += 1 if fatigue or nausea: cold_score += 1 // Compare scores and determine diagnosis -```cpp +``` --- @@ -485,7 +485,7 @@ if fatigue or nausea: cold_score += 1 - [ ] Multiple criteria evaluation **Screening Flow:** -```cpp +``` If experience < 2 AND education < BS AND skills < 2: REJECT Else if experience >= 3 OR education >= BS: @@ -498,7 +498,7 @@ Else if experience >= 3 OR education >= BS: PHONE_SCREEN Else: HOLD -```cpp +``` --- @@ -524,7 +524,7 @@ Else: --- - **Congratulations! You've built intelligent decision systems!** + **Congratulations! You've built intelligent decision systems!** *Next: Repetitive problems with loop-based algorithms and patterns! * @@ -566,7 +566,7 @@ Expected implementation provided. ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/stage-3/level-6/lesson.md b/lessons/c-c++/stage-3/level-6/lesson.md index 52c4e7c..52d3131 100644 --- a/lessons/c-c++/stage-3/level-6/lesson.md +++ b/lessons/c-c++/stage-3/level-6/lesson.md @@ -85,7 +85,7 @@ Create a program that generates different star patterns based on user input: Ask for pattern type and size, then display the pattern. **Example:** -```cpp +``` Enter pattern type (1-4): 1 Enter size: 5 @@ -94,7 +94,7 @@ Enter size: 5 *** **** ***** -```cpp +``` **Your Task:** 1. Write pseudocode for pattern generation algorithms @@ -115,7 +115,7 @@ Create a program that generates number patterns: Display the pattern up to a user-specified limit. **Example:** -```cpp +``` Enter pattern type (1-4): 2 Enter size: 5 @@ -123,7 +123,7 @@ Enter size: 5 1 x 2 = 2 ... 5 x 5 = 25 -```cpp +``` **Your Task:** 1. Write pseudocode for number pattern algorithms @@ -142,7 +142,7 @@ Create a program that calculates statistics for a series of numbers: - [ ] Show final summary **Example:** -```cpp +``` Enter numbers (enter -1 to stop): Number 1: 10 Count: 1, Sum: 10, Avg: 10.0, Min: 10, Max: 10 @@ -158,7 +158,7 @@ Sum: 30 Average: 15.0 Minimum: 10 Maximum: 20 -```cpp +``` **Your Task:** 1. Write pseudocode for statistics calculation loop @@ -179,7 +179,7 @@ Simulate growth over multiple years, showing: - [ ] Total growth over time **Example:** -```cpp +``` Enter initial population: 1000 Enter annual growth rate (%): 5 Enter years to simulate: 10 @@ -190,7 +190,7 @@ Year 2: 1050 → 1102 (+52) Year 10: 1628 → 1709 (+81) Total growth: 709 people -```cpp +``` **Your Task:** 1. Write pseudocode for growth simulation loop @@ -210,14 +210,14 @@ Create a program that searches for a target value in an array: - [ ] Show search efficiency **Example:** -```cpp +``` Enter array size: 5 Enter 5 numbers: 10 20 30 40 50 Enter target to search: 30 Target 30 found at position 3 Comparisons made: 3 -```cpp +``` **Your Task:** 1. Write pseudocode for linear search algorithm @@ -238,7 +238,7 @@ Create a savings account simulator with monthly compounding: Show balance each month and final totals. **Example:** -```cpp +``` Enter initial deposit: 1000 Enter monthly deposit: 100 Enter annual interest rate (%): 6 @@ -251,7 +251,7 @@ Month 24: Balance $3,422.19 Total deposited: $3,400.00 Total interest earned: $422.19 -```cpp +``` **Your Task:** 1. Write pseudocode for savings simulation @@ -263,7 +263,7 @@ Total interest earned: $422.19 ### Loop Algorithm Guidelines **For Loop Structure:** -```cpp +``` Algorithm: Pattern Generator 1. Get size/input parameters 2. For i from 1 to size: @@ -271,10 +271,10 @@ Algorithm: Pattern Generator i. Print pattern element b. Move to next line 3. End pattern -```cpp +``` **While Loop Structure:** -```cpp +``` Algorithm: Data Processor 1. Initialize variables 2. While condition is true: @@ -282,7 +282,7 @@ Algorithm: Data Processor b. Update variables c. Check termination condition 3. Display final results -```cpp +``` --- @@ -353,22 +353,22 @@ Algorithm: Data Processor - [ ] Careful spacing and alignment **Right Triangle Pattern:** -```cpp +``` For i from 1 to size: For j from 1 to i: Print "*" Print newline -```cpp +``` **Pyramid Pattern:** -```cpp +``` For i from 1 to size: For spaces from 1 to (size-i): Print " " For stars from 1 to (2*i-1): Print "*" Print newline -```cpp +``` --- @@ -380,12 +380,12 @@ For i from 1 to size: - [ ] Variable increment patterns **Multiplication Table:** -```cpp +``` For i from 1 to size: For j from 1 to size: Print i + " x " + j + " = " + (i*j) Print newline -```cpp +``` --- @@ -397,7 +397,7 @@ For i from 1 to size: - [ ] Multiple statistics to track **Loop Structure:** -```cpp +``` Initialize: count=0, sum=0, min=MAX, max=MIN While true: Get number @@ -408,7 +408,7 @@ While true: if number > max: max = number Display current stats Display final summary -```cpp +``` --- @@ -420,14 +420,14 @@ Display final summary - [ ] Cumulative tracking **Growth Loop:** -```cpp +``` current_pop = initial For year from 1 to years: growth = current_pop * (rate/100) new_pop = current_pop + growth Display year, current_pop, new_pop, growth current_pop = new_pop -```cpp +``` --- @@ -439,7 +439,7 @@ For year from 1 to years: - [ ] Early termination on find **Search Algorithm:** -```cpp +``` found = false position = -1 comparisons = 0 @@ -453,7 +453,7 @@ If found: Display position and comparisons Else: Display not found -```cpp +``` --- @@ -465,7 +465,7 @@ Else: - [ ] Interest calculation per month **Monthly Simulation:** -```cpp +``` balance = initial_deposit total_deposited = initial_deposit monthly_rate = annual_rate / 100 / 12 @@ -480,7 +480,7 @@ For month from 1 to (years * 12): balance += interest Display month details -```cpp +``` --- @@ -506,7 +506,7 @@ For month from 1 to (years * 12): --- - **Congratulations! You've mastered repetitive algorithms!** + **Congratulations! You've mastered repetitive algorithms!** *Next: Complex system problems with multi-component integration! * @@ -548,7 +548,7 @@ Expected implementation provided. ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/stage-3/level-7/lesson.md b/lessons/c-c++/stage-3/level-7/lesson.md index 7485202..af633a6 100644 --- a/lessons/c-c++/stage-3/level-7/lesson.md +++ b/lessons/c-c++/stage-3/level-7/lesson.md @@ -84,7 +84,7 @@ Create a comprehensive student management system with: - [ ] Student search and modification **Example:** -```cpp +``` === Student Management System === 1. Register Student 2. Add Grades @@ -100,7 +100,7 @@ Enter number of courses: 3 Enter courses: Math Physics Chemistry Student registered successfully! -```cpp +``` **Your Task:** 1. Write pseudocode for the complete student management system @@ -121,7 +121,7 @@ Create an inventory system for a store with: - [ ] Product search and modification **Example:** -```cpp +``` === Inventory Management === 1. Add Product 2. Update Stock @@ -136,7 +136,7 @@ Enter quantity to sell: 2 Sale processed! Total: $29.98 Stock updated: Widget (8 remaining) -```cpp +``` **Your Task:** 1. Write pseudocode for inventory system integration @@ -158,7 +158,7 @@ Create a banking system with multiple account types: - [ ] Balance inquiries **Example:** -```cpp +``` === Banking System === 1. Create Account 2. Deposit @@ -176,7 +176,7 @@ Amount to transfer: 500 Transfer successful! Account 1001 balance: $1,500.00 Account 1002 balance: $2,500.00 -```cpp +``` **Your Task:** 1. Write pseudocode for banking system components @@ -198,7 +198,7 @@ Create a hospital management system with: - [ ] Patient search and reports **Example:** -```cpp +``` === Hospital Management === 1. Register Patient 2. Schedule Appointment @@ -215,7 +215,7 @@ Enter time: 14:00 Enter doctor: Dr. Smith Appointment scheduled successfully! -```cpp +``` **Your Task:** 1. Write pseudocode for hospital system workflow @@ -237,7 +237,7 @@ Create an online shopping system with: - [ ] Customer reviews and ratings **Example:** -```cpp +``` === E-commerce System === 1. Browse Products 2. Add to Cart @@ -252,7 +252,7 @@ Enter product ID: 2001 Enter quantity: 2 Added to cart! Cart total: $49.98 -```cpp +``` **Your Task:** 1. Write pseudocode for e-commerce system integration @@ -274,7 +274,7 @@ Create a game character management system with: - [ ] Character statistics display **Example:** -```cpp +``` === Character System === 1. Create Character 2. Manage Inventory @@ -291,7 +291,7 @@ Enter experience gained: 500 Quest completed! Experience: +500 Level up! Now level 5 New stats: HP +20, Attack +5 -```cpp +``` **Your Task:** 1. Write pseudocode for game character system @@ -303,7 +303,7 @@ New stats: HP +20, Attack +5 ### System Architecture Guidelines **Modular Design:** -```cpp +``` System: Complex Application ├── Component 1: Data Management │ ├── Function: Add Data @@ -321,15 +321,15 @@ System: Complex Application ├── Initialize System ├── Process User Requests └── Maintain System State -```cpp +``` **Data Flow Planning:** -```cpp +``` User Input → Validation → Processing → Storage → Output ↓ ↓ ↓ ↓ Error Handling Business Database Display Messages Logic Updates Results -```cpp +``` --- @@ -412,10 +412,10 @@ struct Student { int attendance[365]; // 1 year int course_count; }; -```cpp +``` **Main System Loop:** -```cpp +``` While running: Display menu Get choice @@ -425,7 +425,7 @@ While running: Case 3: Mark attendance Case 4: Generate student report Case 5: Search and display student -```cpp +``` --- @@ -455,14 +455,14 @@ While running: - [ ] Statement Generation (period reports) **Transaction Flow:** -```cpp +``` Validate accounts exist Check sufficient funds Update balances Record transaction in history Update interest calculations Generate confirmation -```cpp +``` --- @@ -476,11 +476,11 @@ Generate confirmation - [ ] Discharge Processing (final reports) **Patient Journey:** -```cpp +``` Registration → Appointment → Doctor Assignment → Treatment → Discharge ↓ ↓ ↓ ↓ ↓ Data Entry Scheduling Assignment Recording Processing -```cpp +``` --- @@ -494,11 +494,11 @@ Registration → Appointment → Doctor Assignment → Treatment → Discharge - [ ] Inventory Integration (stock updates) **Shopping Workflow:** -```cpp +``` Browse → Add to Cart → Checkout → Process Order → Update Inventory ↓ ↓ ↓ ↓ ↓ Catalog Cart Mgmt Payment Order Creation Stock Reduction -```cpp +``` --- @@ -512,11 +512,11 @@ Catalog Cart Mgmt Payment Order Creation Stock Reduction - [ ] Statistics Display (current status) **Character Development:** -```cpp +``` Creation → Questing → Leveling → Equipment → Stats Growth ↓ ↓ ↓ ↓ ↓ Setup Progress Rewards Upgrades Improvements -```cpp +``` --- @@ -548,7 +548,7 @@ Creation → Questing → Leveling → Equipment → Stats Growth --- - **Congratulations! You've built complete integrated systems!** + **Congratulations! You've built complete integrated systems!** *This completes Stage 3! You're now ready for Stage 4: Full Problem Solving with complete applications! * @@ -590,7 +590,7 @@ Expected implementation provided. ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/stage-4/level-1/lesson.md b/lessons/c-c++/stage-4/level-1/lesson.md index ee40361..d39fd21 100644 --- a/lessons/c-c++/stage-4/level-1/lesson.md +++ b/lessons/c-c++/stage-4/level-1/lesson.md @@ -81,7 +81,7 @@ typedef struct { int student_count; char filename[100]; } GradeBook; -```cpp +``` ### Function Modules - [ ] **File Operations**: `save_data()`, `load_data()` @@ -135,7 +135,7 @@ void display_menu(void); int get_user_choice(void); # endif -```cpp +``` ### Implementation File (gradebook.c) ```c @@ -331,7 +331,7 @@ int get_user_choice(void) { scanf("%d", &choice); return choice; } -```cpp +``` ### Main Program (main.c) ```c @@ -411,7 +411,7 @@ int main() { return 0; } -```cpp +``` --- @@ -424,7 +424,7 @@ gcc -o gradebook main.c gradebook.c # Run the program ./gradebook -```cpp +``` ### Test Scenarios 1. **Add Students**: Try adding 2-3 students with different IDs @@ -434,7 +434,7 @@ gcc -o gradebook main.c gradebook.c 5. **Error Handling**: Test invalid IDs, out-of-range grades ### Sample Usage -```cpp +``` === Grade Management System === 1. Add Student 2. Add Grade @@ -461,7 +461,7 @@ Name: Alice Johnson Number of grades: 1 GPA: 95.50 Grades: 95.50 -```cpp +``` --- @@ -555,12 +555,12 @@ Grades: 95.50 5. **Cleanup**: Proper resource management ### Data Flow -```cpp +``` User Input → Validation → Processing → Storage → Display ↓ ↓ ↓ ↓ Error Messages Business File I/O UI Updates and Recovery Logic Operations Feedback -```cpp +``` --- @@ -590,7 +590,7 @@ User Input → Validation → Processing → Storage → Display --- - **Congratulations! You've built your first complete application!** + **Congratulations! You've built your first complete application!** *This is a major milestone - you can now create fully functional programs from scratch! Next: Data processing applications with advanced file operations! * @@ -632,7 +632,7 @@ Expected implementation provided. ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/stage-4/level-2/lesson.md b/lessons/c-c++/stage-4/level-2/lesson.md index 87e348b..409589e 100644 --- a/lessons/c-c++/stage-4/level-2/lesson.md +++ b/lessons/c-c++/stage-4/level-2/lesson.md @@ -93,7 +93,7 @@ typedef struct { char top_product[MAX_PRODUCT_NAME]; float top_product_revenue; } SalesStats; -```cpp +``` ### Function Modules - [ ] **File Operations**: `load_csv()`, `save_report()` @@ -163,7 +163,7 @@ int get_user_choice(void); void display_records(const SalesData *data, int limit); # endif -```cpp +``` ### Implementation File (sales_analyzer.c) ```c @@ -546,7 +546,7 @@ void analyze_by_product(const SalesData *data) { current_product, product_sales, product_revenue, avg_price); } } -```cpp +``` ### Main Program (main.c) ```c @@ -642,7 +642,7 @@ int main() { free_sales_data(&data); return 0; } -```cpp +``` --- @@ -659,7 +659,7 @@ Date,Product,Quantity,UnitPrice 2024-01-03,Monitor,1,299.99 2024-01-04,Laptop,3,999.99 2024-01-04,Mouse,4,25.50 -```cpp +``` ### Compilation Instructions ``` @@ -668,7 +668,7 @@ gcc -o sales_analyzer main.c sales_analyzer.c -lm # Run the program ./sales_analyzer -```cpp +``` ### Test Scenarios 1. **Load Data**: Import the sample CSV file @@ -763,20 +763,20 @@ gcc -o sales_analyzer main.c sales_analyzer.c -lm ## Code Walkthrough ### Data Processing Pipeline -```cpp +``` CSV File → Parse Records → Validate Data → Store in Memory ↓ ↓ ↓ ↓ Error Clean Data Validated In-Memory Handling Extraction Records Database -```cpp +``` ### Analysis Workflow -```cpp +``` Raw Data → Statistical Calculations → Grouping Operations → Report Generation ↓ ↓ ↓ ↓ Data Loading Summary Stats Date/Product Formatted Output Validation & Averages Analysis & File Export -```cpp +``` --- @@ -806,7 +806,7 @@ Validation & Averages Analysis & File Export --- - **Congratulations! You've built a powerful data processing application!** + **Congratulations! You've built a powerful data processing application!** *Next: Mathematical applications with advanced formula implementations! * @@ -848,7 +848,7 @@ Expected implementation provided. ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/stage-4/level-3/lesson.md b/lessons/c-c++/stage-4/level-3/lesson.md index 105c7db..27f825c 100644 --- a/lessons/c-c++/stage-4/level-3/lesson.md +++ b/lessons/c-c++/stage-4/level-3/lesson.md @@ -89,7 +89,7 @@ typedef struct { double min; double max; } StatisticalData; -```cpp +``` ### Function Modules - [ ] **Calculator**: `scientific_calc()`, `basic_arithmetic()` @@ -188,7 +188,7 @@ int get_user_choice(void); void clear_input_buffer(void); # endif -```cpp +``` ### Implementation File (math_toolbox.c) ```c @@ -554,7 +554,7 @@ void clear_input_buffer(void) { int c; while ((c = getchar()) != '\n' && c != EOF); } -```cpp +``` ### Main Program (main.c) ```c @@ -845,7 +845,7 @@ int main() { return 0; } -```cpp +``` --- @@ -858,7 +858,7 @@ gcc -o math_toolbox main.c math_toolbox.c -lm # Run the program ./math_toolbox -```cpp +``` ### Test Scenarios 1. **Scientific Calculator**: Test sin(30), log(100), sqrt(144) @@ -869,7 +869,7 @@ gcc -o math_toolbox main.c math_toolbox.c -lm 6. **Number Theory**: Check if 17 is prime, factorize 60 ### Sample Usage -```cpp +``` === Math Toolbox === 1. Scientific Calculator 2. Equation Solver @@ -891,7 +891,7 @@ Solve ax² + bx + c = 0 Enter a, b, c: 1 5 6 Equation: 1.00x² + 5.00x + 6.00 = 0 Roots: -2.0000, -3.0000 -```cpp +``` --- @@ -983,20 +983,20 @@ Roots: -2.0000, -3.0000 ## Code Walkthrough ### Mathematical Computation Flow -```cpp +``` User Input → Validation → Mathematical Calculation → Precision Check → Formatted Output ↓ ↓ ↓ ↓ ↓ Input Parsing Constraint Algorithm Execution Rounding/Precision Display Results and Cleaning Checking and Processing Error Handling with Units -```cpp +``` ### Algorithm Selection -```cpp +``` Problem Type → Algorithm Choice → Implementation → Testing → Optimization ↓ ↓ ↓ ↓ ↓ Mathematical Numerical Methods Code Writing Validation Performance Classification Selection & Debugging & Accuracy Tuning -```cpp +``` --- @@ -1026,7 +1026,7 @@ Classification Selection & Debugging & Accuracy Tuning --- - **Congratulations! You've built a comprehensive mathematical application!** + **Congratulations! You've built a comprehensive mathematical application!** *Next: Interactive applications with advanced user interfaces! * @@ -1068,7 +1068,7 @@ Expected implementation provided. ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/stage-4/level-4/lesson.md b/lessons/c-c++/stage-4/level-4/lesson.md index 9e7af5c..406bbeb 100644 --- a/lessons/c-c++/stage-4/level-4/lesson.md +++ b/lessons/c-c++/stage-4/level-4/lesson.md @@ -130,7 +130,7 @@ typedef struct { int goal_count; char data_file[256]; } BudgetTracker; -```cpp +``` ### Function Modules - [ ] **User Interface**: `display_main_menu()`, `handle_navigation()` @@ -272,7 +272,7 @@ double get_positive_amount(const char *prompt); void display_help(void); # endif -```cpp +``` ### Implementation File (budget_tracker.c) ```c @@ -804,7 +804,7 @@ int load_data(BudgetTracker *tracker) { printf(" Data loaded successfully!\n"); return 1; } -```cpp +``` ### Main Program (main.c) ```c @@ -1077,7 +1077,7 @@ void display_budget_vs_actual(const BudgetTracker *tracker) { display_budget_status(tracker); } -```cpp +``` --- @@ -1090,7 +1090,7 @@ gcc -o budget_tracker main.c budget_tracker.c # Run the program ./budget_tracker -```cpp +``` ### Test Scenarios 1. **Setup**: Add a checking account with $1000 balance @@ -1101,7 +1101,7 @@ gcc -o budget_tracker main.c budget_tracker.c 6. **Persistence**: Save and reload data ### Sample Usage Flow -```cpp +``` === Main Menu === 1. View Dashboard 2. Manage Accounts @@ -1122,7 +1122,7 @@ Account type: Enter type (1-4): 1 Enter starting balance: $1000 Account 'My Checking' added successfully! -```cpp +``` --- @@ -1214,20 +1214,20 @@ Enter starting balance: $1000 ## Code Walkthrough ### Application Flow -```cpp +``` Start → Load Data → Main Menu Loop → Feature Selection → Sub-Menu Navigation ↓ ↓ ↓ ↓ ↓ Initialize File I/O User Choice Process Request Context Menus Structures Operations Validation Execute Action User Input -```cpp +``` ### Data Management -```cpp +``` User Actions → Input Validation → Data Processing → Storage Update → UI Refresh ↓ ↓ ↓ ↓ ↓ Menu Selection Constraint Business Logic File I/O Display Update and Input Checking Calculations Operations Results -```cpp +``` --- @@ -1257,7 +1257,7 @@ and Input Checking Calculations Operations Results --- - **Congratulations! You've built a professional interactive application!** + **Congratulations! You've built a professional interactive application!** *Next: Decision support applications with intelligent recommendations! * @@ -1299,7 +1299,7 @@ Expected implementation provided. ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/stage-4/level-5/lesson.md b/lessons/c-c++/stage-4/level-5/lesson.md index 8c941f5..7d37d40 100644 --- a/lessons/c-c++/stage-4/level-5/lesson.md +++ b/lessons/c-c++/stage-4/level-5/lesson.md @@ -117,7 +117,7 @@ typedef struct { double monthly_income; char analysis_period[20]; } SmartAnalyzer; -```cpp +``` ### Function Modules - [ ] **Data Analysis**: `analyze_spending_patterns()`, `detect_anomalies()` @@ -235,7 +235,7 @@ int compare_dates(const char *date1, const char *date2); void get_current_date(char *date); # endif -```cpp +``` ### Implementation File (smart_analyzer.c) ```c @@ -775,7 +775,7 @@ void get_current_date(char *date) { struct tm *tm_info = localtime(&t); strftime(date, 11, "%Y-%m-%d", tm_info); } -```cpp +``` ### Main Program (main.c) ```c @@ -861,7 +861,7 @@ int main() { return 0; } -```cpp +``` --- @@ -874,7 +874,7 @@ gcc -o smart_analyzer main.c smart_analyzer.c -lm # Run the program ./smart_analyzer -```cpp +``` ### Test Scenarios 1. **Dashboard**: View overall financial health and forecasts @@ -885,7 +885,7 @@ gcc -o smart_analyzer main.c smart_analyzer.c -lm 6. **Report**: Generate comprehensive financial analysis ### Sample Analysis Output -```cpp +``` FINANCIAL DASHBOARD ════════════════════════ Monthly Income: $5000.00 @@ -898,7 +898,7 @@ Risk Level: Low FORECASTS Next Month Expenses: $1289.34 Savings Potential: $234.56 -```cpp +``` --- @@ -988,20 +988,20 @@ Savings Potential: $234.56 ## Code Walkthrough ### Intelligence Pipeline -```cpp +``` Data Collection → Pattern Recognition → Analysis & Scoring → Recommendation Generation → User Presentation ↓ ↓ ↓ ↓ ↓ Expense Loading Trend Detection Financial Health Personalized Advice Interactive Display & Validation & Anomaly Finding Assessment & Risk Priority Ranking & Guidance -```cpp +``` ### Decision Support Flow -```cpp +``` User Goals → Spending Analysis → Risk Assessment → Recommendation Filtering → Actionable Advice ↓ ↓ ↓ ↓ ↓ Goal Input Pattern Recognition Vulnerability Personalization Implementation Collection & Trend Analysis Analysis & Scoring & Prioritization Guidance -```cpp +``` --- @@ -1031,7 +1031,7 @@ Collection & Trend Analysis Analysis & Scoring & Prioritization Gui --- - **Congratulations! You've built an intelligent decision support system!** + **Congratulations! You've built an intelligent decision support system!** *Next: Automated applications with task scheduling and batch processing! * @@ -1073,7 +1073,7 @@ Expected implementation provided. ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/stage-4/level-6/lesson.md b/lessons/c-c++/stage-4/level-6/lesson.md index 2faafa8..b3a7f05 100644 --- a/lessons/c-c++/stage-4/level-6/lesson.md +++ b/lessons/c-c++/stage-4/level-6/lesson.md @@ -141,7 +141,7 @@ typedef struct { char log_file[256]; int automation_enabled; } AutomationSuite; -```cpp +``` ### Function Modules - [ ] **Task Scheduler**: `schedule_task()`, `execute_pending_tasks()` @@ -302,7 +302,7 @@ long long get_file_size(const char *filename); int copy_file(const char *source, const char *dest); # endif -```cpp +``` ### Implementation File (automation_suite.c) ```c @@ -842,7 +842,7 @@ int copy_file(const char *source, const char *dest) { fclose(dst); return 1; } -```cpp +``` ### Main Program (main.c) ```c @@ -1030,7 +1030,7 @@ void generate_backup_report(const AutomationSuite *suite) { fclose(report); printf(" Backup report generated: backup_report.txt\n"); } -```cpp +``` --- @@ -1043,7 +1043,7 @@ gcc -o productivity_suite main.c automation_suite.c # Run the program ./productivity_suite -```cpp +``` ### Test Scenarios 1. **Task Manager**: View scheduled tasks and their status @@ -1054,7 +1054,7 @@ gcc -o productivity_suite main.c automation_suite.c 6. **System Health**: Check overall system status ### Sample Automation Flow -```cpp +``` === Main Menu === 1. Task Manager ... @@ -1065,7 +1065,7 @@ Enter your choice (1-8): 6 Generating Productivity Report... Productivity report generated: productivity_report.txt Automation cycle completed -```cpp +``` --- @@ -1161,20 +1161,20 @@ Enter your choice (1-8): 6 ## Code Walkthrough ### Automation Engine Flow -```cpp +``` Initialization → Schedule Loading → Main Loop → Time Check → Task Execution ↓ ↓ ↓ ↓ ↓ System Setup Task Queue User Input Due Tasks Function Call Configuration Management Processing Selection & Monitoring -```cpp +``` ### Scheduling Algorithm -```cpp +``` Task Queue → Time Comparison → Priority Sorting → Resource Check → Execution ↓ ↓ ↓ ↓ ↓ Pending Tasks Schedule Match High Priority Available Run Task Identification Comparison Task Selection Resources & Update -```cpp +``` --- @@ -1204,7 +1204,7 @@ Identification Comparison Task Selection Resources & Update --- - **Congratulations! You've built a comprehensive automation system!** + **Congratulations! You've built a comprehensive automation system!** *Next: Capstone project - bringing together all skills in a major application! * @@ -1246,7 +1246,7 @@ Expected implementation provided. ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/stage-4/level-7/lesson.md b/lessons/c-c++/stage-4/level-7/lesson.md index 3728416..53645b4 100644 --- a/lessons/c-c++/stage-4/level-7/lesson.md +++ b/lessons/c-c++/stage-4/level-7/lesson.md @@ -101,7 +101,7 @@ typedef struct { AlertSystem *alerts; ImportExport *data_handler; } FinanceApplication; -```cpp +``` ### Key Data Structures ```c @@ -195,7 +195,7 @@ typedef struct { double alert_price_high; double alert_price_low; } Investment; -```cpp +``` ### Advanced Features Structure ```c @@ -204,16 +204,16 @@ typedef struct { double monthly_spending_trend; double income_stability_index; char spending_personality[50]; - + // Predictive Modeling double next_month_prediction; double savings_potential; char risk_profile[20]; - + // Anomaly Detection Transaction anomalies[100]; int anomaly_count; - + // Insights char top_insights[10][200]; int insight_count; @@ -223,16 +223,16 @@ typedef struct { // Automated Tasks ScheduledTask tasks[20]; int task_count; - + // Alert Rules AlertRule alerts[50]; int alert_count; - + // Recurring Transactions RecurringTransaction recurring[100]; int recurring_count; } AutomationRules; -```cpp +``` --- @@ -340,7 +340,7 @@ int update_account_balance(FinanceData *data, int account_id, double amount, Tra void display_accounts(const FinanceData *data); // Transaction management -int add_transaction(FinanceData *data, const char *date, const char *description, +int add_transaction(FinanceData *data, const char *date, const char *description, TransactionType type, double amount, int account_id, int category_id); void display_transactions(const FinanceData *data, int limit); double calculate_account_balance(const FinanceData *data, int account_id); @@ -356,7 +356,7 @@ void update_goal_progress(FinanceData *data, int goal_id, double amount); void display_goals(const FinanceData *data); // Investment tracking -int add_investment(FinanceData *data, const char *symbol, const char *name, +int add_investment(FinanceData *data, const char *symbol, const char *name, double shares, double avg_cost, double current_price); void update_investment_prices(FinanceData *data); void display_portfolio(const FinanceData *data); @@ -385,7 +385,7 @@ int validate_date(const char *date); void format_currency(char *buffer, double amount); # endif -```cpp +``` ### Core Implementation File (finance_manager.c) ```c @@ -443,7 +443,7 @@ void display_accounts(const FinanceData *data) { char balance_str[20]; format_currency(balance_str, acc->balance); - + printf("%-3d %-20s %-12s %-15s %-15s\n", acc->id, acc->name, type_str, balance_str, acc->institution); } @@ -584,7 +584,7 @@ void display_budget_status(const FinanceData *data) { for (int i = 0; i < data->budget_count; i++) { const Budget *budget = &data->budgets[i]; double percent_used = calculate_percentage(budget->spent_amount, budget->budgeted_amount); - + char allocated_str[20], spent_str[20], remaining_str[20]; format_currency(allocated_str, budget->budgeted_amount); format_currency(spent_str, budget->spent_amount); @@ -628,7 +628,7 @@ void update_goal_progress(FinanceData *data, int goal_id, double amount) { data->goals[i].current_amount += amount; data->goals[i].progress_percentage = calculate_percentage( data->goals[i].current_amount, data->goals[i].target_amount); - + if (data->goals[i].current_amount >= data->goals[i].target_amount && !data->goals[i].achieved) { data->goals[i].achieved = 1; get_current_date(data->goals[i].achieved_date); @@ -647,7 +647,7 @@ void display_goals(const FinanceData *data) { printf("\n FINANCIAL GOALS\n"); printf("═══════════════════════════════════════════════════════════════════════════════\n"); - printf("%-25s %-12s %-12s %-10s %-12s %-10s\n", + printf("%-25s %-12s %-12s %-10s %-12s %-10s\n", "Goal", "Target", "Current", "Progress", "Monthly", "Status"); printf("───────────────────────────────────────────────────────────────────────────────\n"); @@ -661,7 +661,7 @@ void display_goals(const FinanceData *data) { const char *status = goal->achieved ? " Achieved" : "⏳ In Progress"; printf("%-25s %-12s %-12s %6.1f%% %-12s %-10s\n", - goal->name, target_str, current_str, goal->progress_percentage, + goal->name, target_str, current_str, goal->progress_percentage, monthly_str, status); } } @@ -716,7 +716,7 @@ void display_portfolio(const FinanceData *data) { format_currency(gain_str, inv->gain_loss); printf("%-8s %-20s %6.2f %-12s %-12s %-10s %-10s\n", - inv->symbol, inv->name, inv->shares_owned, cost_str, price_str, + inv->symbol, inv->name, inv->shares_owned, cost_str, price_str, value_str, gain_str); total_value += inv->current_value; @@ -802,7 +802,7 @@ void generate_financial_report(const FinanceData *data) { } fprintf(report, "Total Portfolio Value: $%.2f\n", total_portfolio_value); fprintf(report, "Total Gain/Loss: $%.2f\n", total_portfolio_gain); - fprintf(report, "Portfolio Return: %.2f%%\n", + fprintf(report, "Portfolio Return: %.2f%%\n", calculate_percentage(total_portfolio_gain, total_portfolio_value - total_portfolio_gain)); } @@ -826,7 +826,7 @@ void analyze_spending_patterns(const FinanceData *data) { strncpy(month_str, trans->date + 5, 2); month_str[2] = '\0'; int month = atoi(month_str) - 1; // 0-based - + if (month >= 0 && month < 12) { monthly_totals[month] += trans->amount; transaction_counts[month]++; @@ -837,10 +837,10 @@ void analyze_spending_patterns(const FinanceData *data) { printf("Monthly Spending Summary:\n"); const char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; - + for (int i = 0; i < 12; i++) { if (transaction_counts[i] > 0) { - printf("%s: $%.2f (%d transactions)\n", + printf("%s: $%.2f (%d transactions)\n", months[i], monthly_totals[i], transaction_counts[i]); } } @@ -854,11 +854,11 @@ void analyze_spending_patterns(const FinanceData *data) { months_with_data++; } } - + if (months_with_data > 0) { avg_monthly /= months_with_data; printf("\nAverage Monthly Spending: $%.2f\n", avg_monthly); - + // Simple personality analysis if (avg_monthly < 1000) { printf(" Spending Personality: Conservative spender\n"); @@ -887,16 +887,16 @@ int save_financial_data(const FinanceData *data) { // Write accounts fwrite(data->accounts, sizeof(Account), data->account_count, file); - + // Write transactions fwrite(data->transactions, sizeof(Transaction), data->transaction_count, file); - + // Write budgets fwrite(data->budgets, sizeof(Budget), data->budget_count, file); - + // Write goals fwrite(data->goals, sizeof(Goal), data->goal_count, file); - + // Write investments fwrite(data->investments, sizeof(Investment), data->investment_count, file); @@ -921,16 +921,16 @@ int load_financial_data(FinanceData *data) { // Read accounts fread(data->accounts, sizeof(Account), data->account_count, file); - + // Read transactions fread(data->transactions, sizeof(Transaction), data->transaction_count, file); - + // Read budgets fread(data->budgets, sizeof(Budget), data->budget_count, file); - + // Read goals fread(data->goals, sizeof(Goal), data->goal_count, file); - + // Read investments fread(data->investments, sizeof(Investment), data->investment_count, file); @@ -986,11 +986,11 @@ void display_dashboard(const FinanceData *data) { // Quick insights printf("\n QUICK INSIGHTS\n"); printf("═══════════════════\n"); - + if (data->budget_count > 0) { int budgets_on_track = 0; for (int i = 0; i < data->budget_count; i++) { - double utilization = calculate_percentage(data->budgets[i].spent_amount, + double utilization = calculate_percentage(data->budgets[i].spent_amount, data->budgets[i].budgeted_amount); if (utilization <= 100.0) budgets_on_track++; } @@ -1041,7 +1041,7 @@ int validate_date(const char *date) { // Basic date validation (YYYY-MM-DD format) if (strlen(date) != 10) return 0; if (date[4] != '-' || date[7] != '-') return 0; - + // Could add more sophisticated validation return 1; } @@ -1053,7 +1053,7 @@ void format_currency(char *buffer, double amount) { sprintf(buffer, "$%.2f", amount); } } -```cpp +``` ### Main Program (main.c) ```c @@ -1062,7 +1062,7 @@ void format_currency(char *buffer, double amount) { int main() { FinanceData finance_data; strcpy(finance_data.data_file, "finance_data.dat"); - + // Initialize data finance_data.account_count = 0; finance_data.transaction_count = 0; @@ -1100,12 +1100,12 @@ int main() { if (acc_choice == 1) { char name[100], institution[100]; int type_choice; - + printf("Enter account name: "); scanf(" %[^\n]", name); printf("Account type (1-Checking, 2-Savings, 3-Credit Card, 4-Investment, 5-Loan, 6-Retirement): "); scanf("%d", &type_choice); - + AccountType type; switch (type_choice) { case 1: type = CHECKING; break; @@ -1116,15 +1116,15 @@ int main() { case 6: type = RETIREMENT; break; default: printf("Invalid type!\n"); continue; } - + printf("Enter institution: "); scanf(" %[^\n]", institution); - + add_account(&finance_data, name, type, institution); } else if (acc_choice == 2) { display_accounts(&finance_data); } - + printf("\nPress Enter to continue..."); getchar(); getchar(); break; @@ -1141,25 +1141,25 @@ int main() { char date[11], description[200]; int type_choice, account_id, category_id; double amount; - + printf("Enter date (YYYY-MM-DD): "); scanf("%s", date); printf("Enter description: "); scanf(" %[^\n]", description); printf("Transaction type (1-Income, 2-Expense, 3-Transfer): "); scanf("%d", &type_choice); - - TransactionType type = (type_choice == 1) ? INCOME : + + TransactionType type = (type_choice == 1) ? INCOME : (type_choice == 2) ? EXPENSE : TRANSFER; - + printf("Enter amount: $"); scanf("%lf", &amount); printf("Enter account ID: "); scanf("%d", &account_id); - + // For simplicity, use category_id = 1 (would have category management) category_id = 1; - + add_transaction(&finance_data, date, description, type, amount, account_id, category_id); } else if (trans_choice == 2) { printf("Enter number of transactions to view (0 for all): "); @@ -1167,7 +1167,7 @@ int main() { scanf("%d", &limit); display_transactions(&finance_data, limit); } - + printf("\nPress Enter to continue..."); getchar(); getchar(); break; @@ -1184,23 +1184,23 @@ int main() { char name[100], period[20]; double amount; int category_id; - + printf("Enter budget name: "); scanf(" %[^\n]", name); printf("Enter budgeted amount: $"); scanf("%lf", &amount); printf("Enter period (Monthly/Weekly): "); scanf("%s", period); - + // For simplicity, use category_id = 1 category_id = 1; - + create_budget(&finance_data, name, amount, period, category_id); } else if (budget_choice == 2) { update_budget_spending(&finance_data); display_budget_status(&finance_data); } - + printf("\nPress Enter to continue..."); getchar(); getchar(); break; @@ -1217,7 +1217,7 @@ int main() { if (goal_choice == 1) { char name[200], target_date[11]; double target, monthly; - + printf("Enter goal name: "); scanf(" %[^\n]", name); printf("Enter target amount: $"); @@ -1226,7 +1226,7 @@ int main() { scanf("%s", target_date); printf("Enter monthly contribution: $"); scanf("%lf", &monthly); - + add_goal(&finance_data, name, target, target_date, monthly); } else if (goal_choice == 2) { display_goals(&finance_data); @@ -1237,10 +1237,10 @@ int main() { printf("Enter amount to add: $"); double amount; scanf("%lf", &amount); - + update_goal_progress(&finance_data, goal_id, amount); } - + printf("\nPress Enter to continue..."); getchar(); getchar(); break; @@ -1256,7 +1256,7 @@ int main() { if (inv_choice == 1) { char symbol[10], name[100]; double shares, avg_cost, current_price; - + printf("Enter symbol: "); scanf("%s", symbol); printf("Enter name: "); @@ -1267,12 +1267,12 @@ int main() { scanf("%lf", &avg_cost); printf("Enter current price per share: $"); scanf("%lf", ¤t_price); - + add_investment(&finance_data, symbol, name, shares, avg_cost, current_price); } else if (inv_choice == 2) { display_portfolio(&finance_data); } - + printf("\nPress Enter to continue..."); getchar(); getchar(); break; @@ -1290,7 +1290,7 @@ int main() { } else if (report_choice == 2) { analyze_spending_patterns(&finance_data); } - + printf("\nPress Enter to continue..."); getchar(); getchar(); break; @@ -1311,7 +1311,7 @@ int main() { } else if (data_choice == 3) { export_to_csv(&finance_data, "finance_export.csv"); } - + printf("\nPress Enter to continue..."); getchar(); getchar(); break; @@ -1335,7 +1335,7 @@ int main() { return 0; } -```cpp +``` --- @@ -1348,7 +1348,7 @@ gcc -o finance_manager main.c finance_manager.c # Run the program ./finance_manager -```cpp +``` ### Test Scenarios 1. **Setup**: Add checking and savings accounts @@ -1360,7 +1360,7 @@ gcc -o finance_manager main.c finance_manager.c 7. **Data**: Save and reload financial data ### Sample Usage Flow -```cpp +``` === Main Menu === 1. Dashboard ... @@ -1374,7 +1374,7 @@ Enter account name: My Checking Account type (1-Checking, 2-Savings, 3-Credit Card, 4-Investment, 5-Loan, 6-Retirement): 1 Enter institution: Bank of America Account 'My Checking' added successfully! -```cpp +``` --- @@ -1492,21 +1492,21 @@ Enter institution: Bank of America ## Code Walkthrough ### System Architecture Flow -```cpp +``` User Interface Layer → Business Logic Layer → Data Access Layer → Persistence Layer ↓ ↓ ↓ ↓ Menu Navigation Financial Data Structures File I/O & Input Handling Calculations & Memory Management & Backup -```cpp +``` ### Financial Processing Pipeline -```cpp +``` Transaction Input → Validation → Categorization → Account Update → Budget Check → Goal Update → Analytics Update ↓ ↓ ↓ ↓ ↓ ↓ ↓ Data Entry Rule Validation Smart Tagging Balance Calc Variance Progress Trend Analysis & Capture & Constraint & Learning & Synchronization Analysis Tracking & Forecasting Checking Enforcement Algorithms & Persistence & Alerts -```cpp +``` --- @@ -1538,15 +1538,15 @@ Checking Enforcement Algorithms & Persistence & Al --- - **CONGRATULATIONS! You have completed the comprehensive C/C++ programming curriculum!** + **CONGRATULATIONS! You have completed the comprehensive C/C++ programming curriculum!** - **You are now a MASTER PROGRAMMER!** + **You are now a MASTER PROGRAMMER!** *This capstone project demonstrates your complete mastery of programming concepts, from basic syntax to advanced system design. You can now build any application you can imagine!* -**Your journey doesn't end here - continue learning, building projects, and pushing the boundaries of what you can create!** +**Your journey doesn't end here - continue learning, building projects, and pushing the boundaries of what you can create!** -*Remember: The best programmers are those who never stop learning and never stop creating!* +*Remember: The best programmers are those who never stop learning and never stop creating!* ### How to Run @@ -1586,7 +1586,7 @@ Expected implementation provided. ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/stage-5/level-1/lesson.md b/lessons/c-c++/stage-5/level-1/lesson.md index 1337254..f3ecdb0 100644 --- a/lessons/c-c++/stage-5/level-1/lesson.md +++ b/lessons/c-c++/stage-5/level-1/lesson.md @@ -28,7 +28,7 @@ ### Today's Mission -**Welcome to Stage 5!** +**Welcome to Stage 5!** You've completed Stages 1-4 and learned to: - [ ] Copy and understand code (Stage 1) @@ -59,9 +59,9 @@ By completing this capstone level, you will: Your Level 1 Capstone should: -**Complexity**: Moderate (3-5 main features) -**Code Size**: 500-1500 lines (depending on scope) -**Time Estimate**: 10-15 hours of focused work +**Complexity**: Moderate (3-5 main features) +**Code Size**: 500-1500 lines (depending on scope) +**Time Estimate**: 10-15 hours of focused work **Purpose**: Demonstrate mastery of Core Programming Concepts --- @@ -210,7 +210,7 @@ Your capstone will be evaluated on: Before coding, submit a proposal addressing: -```cpp +``` PROJECT TITLE: [Name] DOMAIN: [Category - e.g., Personal Finance, Education] PURPOSE: [What problem does it solve?] @@ -238,7 +238,7 @@ USER INTERFACE: - [What menus or prompts?] ESTIMATED EFFORT: [X hours of work] -```cpp +``` --- @@ -318,10 +318,10 @@ Once your core capstone is complete, consider these extensions: **Concepts You'll Need:** -From **Stage 1**: Syntax, operators, basic I/O -From **Stage 2**: Loops, conditionals, algorithms -From **Stage 3**: Functions, modularity, code organization -From **Stage 4**: File I/O, data structures, system design +From **Stage 1**: Syntax, operators, basic I/O +From **Stage 2**: Loops, conditionals, algorithms +From **Stage 3**: Functions, modularity, code organization +From **Stage 4**: File I/O, data structures, system design **Review as needed:** - [ ] String manipulation and parsing @@ -408,26 +408,26 @@ From **Stage 4**: File I/O, data structures, system design **Essential Planning Steps:** 1. **Write a Problem Statement** - ```cpp + ``` "My application solves [problem] by [approach] for [users] so that [outcome]." - ```cpp + ``` 2. **Define Core Features** (3-5 minimum) - ```cpp + ``` MUST HAVE (critical): - Feature A - Feature B - + SHOULD HAVE (important): - Feature C - Feature D - + NICE TO HAVE (bonus): - Feature E - ```cpp + ``` 3. **Design Data Structures** ```c @@ -436,16 +436,16 @@ From **Stage 4**: File I/O, data structures, system design char name[100]; // ... other fields }; - + struct Company { Person employees[100]; int employee_count; // ... other fields }; - ```cpp + ``` 4. **Create Architecture Diagram** - ```cpp + ``` USER INPUT ↓ MENU SYSTEM @@ -455,10 +455,10 @@ From **Stage 4**: File I/O, data structures, system design DATA STORAGE (structs) ↓ FILE I/O (persistence) - ```cpp + ``` 5. **Write Pseudocode for Main Functions** - ```cpp + ``` Algorithm: AddNewRecord 1. Get input from user 2. Validate input @@ -466,14 +466,14 @@ From **Stage 4**: File I/O, data structures, system design 4. Add to collection 5. Save to file 6. Display confirmation - + Algorithm: SearchRecords 1. Get search criteria from user 2. Loop through all records 3. Check if record matches criteria 4. Display matching records 5. Ask if user wants to filter further - ```cpp + ``` ### Phase 3: Data Structure Design @@ -520,7 +520,7 @@ void add_entity(EntityManager *manager); void view_entities(EntityManager *manager); void search_entities(EntityManager *manager); void delete_entity(EntityManager *manager); -```cpp +``` ### Phase 4: Implementation Strategy @@ -543,7 +543,7 @@ void delete_entity(EntityManager *manager); **Create a Test Plan:** -```cpp +``` TEST CASE 1: Add New Record Input: Valid record data Expected: Record added, saved to file @@ -560,7 +560,7 @@ Expected: "No records found" message Result: PASS / FAIL ... (20-30 test cases minimum) -```cpp +``` ### Phase 6: Code Quality Checklist @@ -592,9 +592,9 @@ Result: PASS / FAIL - Note which are core vs. bonus 3. **Compilation Instructions** - ```bash + ``` g++ -o myapp main.c -lm - ```cpp + ``` 4. **Usage Guide** - How to run the program @@ -628,14 +628,14 @@ Result: PASS / FAIL **An excellent capstone has:** - **Clear Purpose**: Solves a real or interesting problem - **Complete Implementation**: All features work, no partial functionality - **Robust Error Handling**: Handles edge cases gracefully - **Professional Code**: Well-organized, readable, maintainable - **Thoughtful Design**: Data structures fit the problem - **Thorough Testing**: Documented test cases and results - **Great Documentation**: README, comments, usage guide - **Personal Touch**: Shows creativity and individuality + **Clear Purpose**: Solves a real or interesting problem + **Complete Implementation**: All features work, no partial functionality + **Robust Error Handling**: Handles edge cases gracefully + **Professional Code**: Well-organized, readable, maintainable + **Thoughtful Design**: Data structures fit the problem + **Thorough Testing**: Documented test cases and results + **Great Documentation**: README, comments, usage guide + **Personal Touch**: Shows creativity and individuality --- @@ -668,18 +668,18 @@ Result: PASS / FAIL ## Real-World Capstone Examples ### Example 1: Personal Finance Manager -```cpp +``` PURPOSE: Help track personal spending and savings goals -FEATURES: +FEATURES: - Add/categorize expenses - Set and track savings goals - Generate spending reports - Export to CSV for analysis COMPLEXITY: Moderate (5-7 hours) -```cpp +``` ### Example 2: Quiz Application -```cpp +``` PURPOSE: Interactive quiz system for learning FEATURES: - Load questions from file @@ -687,10 +687,10 @@ FEATURES: - Provide instant feedback - Show statistics and progress COMPLEXITY: Moderate (6-8 hours) -```cpp +``` ### Example 3: Data Processor -```cpp +``` PURPOSE: Analyze CSV files and generate reports FEATURES: - Parse CSV files @@ -699,15 +699,15 @@ FEATURES: - Generate reports - Export results COMPLEXITY: Moderate to Advanced (8-12 hours) -```cpp +``` --- - **Congratulations on reaching Stage 5!** + **Congratulations on reaching Stage 5!** You've completed your programming education journey. Now create something amazing! -*Your capstone project is your proof to the world that you can program.* +*Your capstone project is your proof to the world that you can program.* @@ -756,7 +756,7 @@ Expected implementation provided. ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/stage-5/level-2/lesson.md b/lessons/c-c++/stage-5/level-2/lesson.md index 6b33b51..35bb2e0 100644 --- a/lessons/c-c++/stage-5/level-2/lesson.md +++ b/lessons/c-c++/stage-5/level-2/lesson.md @@ -25,9 +25,9 @@ By the end of this level: ### Project Scope -**Complexity**: Intermediate-Advanced (5-7 features) -**Code Size**: 1500-3000 lines -**Time Estimate**: 15-20 hours +**Complexity**: Intermediate-Advanced (5-7 features) +**Code Size**: 1500-3000 lines +**Time Estimate**: 15-20 hours **Purpose**: Demonstrate advanced integration and system design --- @@ -141,7 +141,7 @@ Pick ONE theme to guide your project: 4. **Optimize ruthlessly** for performance 5. **Document thoroughly** for others to understand -**Ready to build something impressive?** +**Ready to build something impressive?** @@ -189,7 +189,7 @@ Key functions and their purpose: ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/stage-5/level-3/lesson.md b/lessons/c-c++/stage-5/level-3/lesson.md index b0a129f..f0c6f5c 100644 --- a/lessons/c-c++/stage-5/level-3/lesson.md +++ b/lessons/c-c++/stage-5/level-3/lesson.md @@ -25,9 +25,9 @@ By the end of this level: ### Project Scope -**Complexity**: Advanced (7-10 features) -**Code Size**: 2000-4000 lines -**Time Estimate**: 20-25 hours +**Complexity**: Advanced (7-10 features) +**Code Size**: 2000-4000 lines +**Time Estimate**: 20-25 hours **Purpose**: Showcase deep expertise in a specific domain --- @@ -118,7 +118,7 @@ Choose a domain where you have **genuine interest or expertise**: 5. **Build with excellence** in mind 6. **Validate with real users** in that domain -**Ready to become a domain expert?** +**Ready to become a domain expert?** @@ -166,7 +166,7 @@ Key functions and their purpose: ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/stage-5/level-4/lesson.md b/lessons/c-c++/stage-5/level-4/lesson.md index 90ba059..551bfbd 100644 --- a/lessons/c-c++/stage-5/level-4/lesson.md +++ b/lessons/c-c++/stage-5/level-4/lesson.md @@ -24,9 +24,9 @@ Build a **comprehensive system** that integrates everything you've learned while ### Project Scope -**Complexity**: Expert Level (10+ features) -**Code Size**: 3000-5000+ lines -**Time Estimate**: 25-30 hours +**Complexity**: Expert Level (10+ features) +**Code Size**: 3000-5000+ lines +**Time Estimate**: 25-30 hours **Purpose**: Demonstrate mastery of full system development --- @@ -48,11 +48,11 @@ Your project should include: ### Example System Types -**E-Commerce Platform**: Product catalog, shopping cart, order management, payment processing -**Inventory System**: Multi-warehouse tracking, automated reordering, analytics -**Project Management Tool**: Tasks, timelines, resource allocation, collaboration -**Content Management**: Creation, editing, publishing, versioning, permissions -**Analytics Platform**: Data ingestion, processing, visualization, reporting +**E-Commerce Platform**: Product catalog, shopping cart, order management, payment processing +**Inventory System**: Multi-warehouse tracking, automated reordering, analytics +**Project Management Tool**: Tasks, timelines, resource allocation, collaboration +**Content Management**: Creation, editing, publishing, versioning, permissions +**Analytics Platform**: Data ingestion, processing, visualization, reporting --- @@ -63,7 +63,7 @@ Your project should include: - [ ] Build something **you'd be proud to show employers** - [ ] Implement features that **require sophisticated design** -Ready to create your magnum opus? +Ready to create your magnum opus? @@ -111,7 +111,7 @@ Key functions and their purpose: ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/stage-5/level-5/lesson.md b/lessons/c-c++/stage-5/level-5/lesson.md index 728641a..732c28f 100644 --- a/lessons/c-c++/stage-5/level-5/lesson.md +++ b/lessons/c-c++/stage-5/level-5/lesson.md @@ -26,7 +26,7 @@ Learn to **collaborate professionally** and **review code** like production team **Focus**: Taking an existing project and preparing it for team collaboration -**Time Estimate**: 10-15 hours +**Time Estimate**: 10-15 hours **Purpose**: Learn professional software development practices --- @@ -53,7 +53,7 @@ Learn to **collaborate professionally** and **review code** like production team - [ ] Conflict resolution - [ ] Knowledge sharing -Ready to work with others professionally? +Ready to work with others professionally? @@ -101,7 +101,7 @@ Key functions and their purpose: ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/stage-5/level-6/lesson.md b/lessons/c-c++/stage-5/level-6/lesson.md index 61c4eb8..e41d338 100644 --- a/lessons/c-c++/stage-5/level-6/lesson.md +++ b/lessons/c-c++/stage-5/level-6/lesson.md @@ -26,7 +26,7 @@ **Focus**: Contributing to real open source projects or starting your own -**Time Estimate**: 15-20+ hours +**Time Estimate**: 15-20+ hours **Purpose**: Gain real-world experience with professional projects --- @@ -65,7 +65,7 @@ - [ ] Long-term project maintenance - [ ] Community leadership -Ready to make a difference in open source? +Ready to make a difference in open source? @@ -113,7 +113,7 @@ Key functions and their purpose: ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/c-c++/stage-5/level-7/lesson.md b/lessons/c-c++/stage-5/level-7/lesson.md index ce99867..83e0404 100644 --- a/lessons/c-c++/stage-5/level-7/lesson.md +++ b/lessons/c-c++/stage-5/level-7/lesson.md @@ -121,7 +121,7 @@ Now that you've completed your capstone journey: --- -### Congratulations! +### Congratulations! You've completed a comprehensive programming education: @@ -131,7 +131,7 @@ You've completed a comprehensive programming education: - [ ] **Stage 4**: Created problems independently - [ ] **Stage 5**: Built capstone projects professionally -**You are now a programmer.** +**You are now a programmer.** The journey doesn't end here—it's just beginning. Use your skills to: - [ ] Solve real problems @@ -168,7 +168,7 @@ The journey doesn't end here—it's just beginning. Use your skills to: --- -**You did it! Now go build something amazing!** +**You did it! Now go build something amazing!** @@ -216,7 +216,7 @@ Key functions and their purpose: ### Complete Solution -```cpp +``` #include int main() { diff --git a/lessons/csharp/stage-1/level-1/lesson.md b/lessons/csharp/stage-1/level-1/lesson.md index 00b7b70..c013221 100644 --- a/lessons/csharp/stage-1/level-1/lesson.md +++ b/lessons/csharp/stage-1/level-1/lesson.md @@ -19,7 +19,7 @@ Welcome to C#! Today, you'll create your first C# program. C# is a modern, objec Copy the following code EXACTLY as shown into a new file called `hello.cs`: -```csharp +``` using System; class Program { @@ -27,20 +27,20 @@ class Program { Console.WriteLine("Hello, World!"); } } -```csharp +``` ### How to Execute -```bash +``` csc hello.cs ./hello.exe -```csharp +``` Expected output: -```csharp +``` Hello, World! -```csharp +``` ### Success Checklist @@ -61,82 +61,28 @@ Hello, World! ## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown - -### Key Concepts - -- Review the code structure specific to Csharp -- Understand the execution flow -- Learn common pitfalls and solutions - -### Next Steps - -Practice the code and experiment with variations! - ---- - -**Congratulations! Keep coding!** - -### How to Run - -1. Open the code file -2. Review and understand the implementation -3. Execute using: `r` in Vim - -### Additional Content - -Understand the key concepts: +### Solution -- Review each function -- Understand the flow -- Learn the patterns used - -### Code Review - -Key functions and their purpose: - -- Main function: Entry point -- Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```cs +``` using System; class Program { - static void Main() { - Console.WriteLine("Hello, World!"); - } + static void Main() { + Console.WriteLine("Hello, World!"); + } } - ``` -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: +### Explanation -1. **Structure**: The program follows standard csharp conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -### Testing Your Solution +### Success Criteria -Try these test cases to verify your code works correctly: +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding +--- -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs +**Great job! You've completed this lesson!** diff --git a/lessons/csharp/stage-1/level-2/lesson.md b/lessons/csharp/stage-1/level-2/lesson.md index 6a74f2e..07f539e 100644 --- a/lessons/csharp/stage-1/level-2/lesson.md +++ b/lessons/csharp/stage-1/level-2/lesson.md @@ -19,7 +19,7 @@ Now that you know how to run Csharp programs, let's learn about variables! Varia Copy the following code EXACTLY as shown into a new file called `variables.cs`: -```cs +``` using System; class Program { @@ -35,22 +35,22 @@ class Program { Console.WriteLine($"Student status: {isStudent}"); } } -```csharp +``` ### How to Execute -```bash +``` csc variables.cs -```csharp +``` Expected output: -```csharp +``` Hello, Alice! You are 25 years old. Your height is 5.6 feet. Student status: true -```csharp +``` ### Success Checklist @@ -90,82 +90,36 @@ Remember to check the `VIM_CHEATSHEET.md` in the root directory for basic Vim co ## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown - -### Key Concepts - -- Review the code structure specific to Csharp -- Understand the execution flow -- Learn common pitfalls and solutions - -### Next Steps - -Practice the code and experiment with variations! - ---- - -**Congratulations! Keep coding!** - -### How to Run - -1. Open the code file -2. Review and understand the implementation -3. Execute using: `r` in Vim - -### Additional Content - -Understand the key concepts: - -- Review each function -- Understand the flow -- Learn the patterns used - -### Code Review - -Key functions and their purpose: - -- Main function: Entry point -- Helper functions: Support logic +### Solution - -
- -## Answer Key - -### Complete Solution - -```cs +``` using System; class Program { - static void Main() { - Console.WriteLine("Hello, World!"); - } -} + static void Main() { + string name = "Alice"; + int age = 25; + double height = 5.6; + bool isStudent = true; + Console.WriteLine($"Hello, {name}!"); + Console.WriteLine($"You are {age} years old."); + Console.WriteLine($"Your height is {height} feet."); + Console.WriteLine($"Student status: {isStudent}"); + } +} ``` -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: +### Explanation -1. **Structure**: The program follows standard csharp conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -### Testing Your Solution +### Success Criteria -Try these test cases to verify your code works correctly: +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding +--- -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs +**Great job! You've completed this lesson!** diff --git a/lessons/csharp/stage-1/level-3/lesson.md b/lessons/csharp/stage-1/level-3/lesson.md index 1312c0c..13759b6 100644 --- a/lessons/csharp/stage-1/level-3/lesson.md +++ b/lessons/csharp/stage-1/level-3/lesson.md @@ -23,26 +23,26 @@ Master arithmetic operations and use the language as your calculator. **Copy the following code EXACTLY as shown below into `main.cs`** -```csharp +``` using System; class Program { static void Main() { int a = 15; int b = 4; - + Console.WriteLine($"Addition: {a} + {b} = {a + b}"); Console.WriteLine($"Subtraction: {a} - {b} = {a - b}"); Console.WriteLine($"Multiplication: {a} × {b} = {a * b}"); Console.WriteLine($"Division: {a} / {b} = {a / b}"); Console.WriteLine($"Remainder: {a} % {b} = {a % b}"); - + double x = 15.0; double y = 4.0; Console.WriteLine($"Precise Division: {x} / {y} = {x / y}"); } } -```csharp +``` --- @@ -64,26 +64,26 @@ class Program { ### The Complete Code -```csharp +``` using System; class Program { static void Main() { int a = 15; int b = 4; - + Console.WriteLine($"Addition: {a} + {b} = {a + b}"); Console.WriteLine($"Subtraction: {a} - {b} = {a - b}"); Console.WriteLine($"Multiplication: {a} × {b} = {a * b}"); Console.WriteLine($"Division: {a} / {b} = {a / b}"); Console.WriteLine($"Remainder: {a} % {b} = {a % b}"); - + double x = 15.0; double y = 4.0; Console.WriteLine($"Precise Division: {x} / {y} = {x / y}"); } } -```csharp +``` ### What This Code Does @@ -150,46 +150,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```cs -using System; - -class Program { - static void Main() { - Console.WriteLine("Hello, World!"); - } -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard csharp conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/csharp/stage-1/level-4/lesson.md b/lessons/csharp/stage-1/level-4/lesson.md index 9d2228d..b05336a 100644 --- a/lessons/csharp/stage-1/level-4/lesson.md +++ b/lessons/csharp/stage-1/level-4/lesson.md @@ -23,23 +23,23 @@ Make your programs interactive by reading input from users. **Copy the following code EXACTLY as shown below into `main.cs`** -```csharp +``` using System; class Program { static void Main() { Console.Write("Enter your name: "); string name = Console.ReadLine(); - + Console.Write("Enter your age: "); int age = int.Parse(Console.ReadLine()); - + Console.WriteLine($"Hello, {name}!"); Console.WriteLine($"You are {age} years old."); Console.WriteLine($"Next year you'll be {age + 1}."); } } -```csharp +``` --- @@ -61,23 +61,23 @@ class Program { ### The Complete Code -```csharp +``` using System; class Program { static void Main() { Console.Write("Enter your name: "); string name = Console.ReadLine(); - + Console.Write("Enter your age: "); int age = int.Parse(Console.ReadLine()); - + Console.WriteLine($"Hello, {name}!"); Console.WriteLine($"You are {age} years old."); Console.WriteLine($"Next year you'll be {age + 1}."); } } -```csharp +``` ### What This Code Does @@ -144,46 +144,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```cs -using System; - -class Program { - static void Main() { - Console.WriteLine("Hello, World!"); - } -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard csharp conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/csharp/stage-1/level-5/lesson.md b/lessons/csharp/stage-1/level-5/lesson.md index d644d54..da1e0ef 100644 --- a/lessons/csharp/stage-1/level-5/lesson.md +++ b/lessons/csharp/stage-1/level-5/lesson.md @@ -23,14 +23,14 @@ Add decision-making to your programs with if/else statements. **Copy the following code EXACTLY as shown below into `main.cs`** -```csharp +``` using System; class Program { static void Main() { Console.Write("Enter a number: "); int num = int.Parse(Console.ReadLine()); - + if (num > 0) { Console.WriteLine($"{num} is positive"); } else if (num < 0) { @@ -38,7 +38,7 @@ class Program { } else { Console.WriteLine("The number is zero"); } - + if (num % 2 == 0) { Console.WriteLine($"{num} is even"); } else { @@ -46,7 +46,7 @@ class Program { } } } -```csharp +``` --- @@ -68,14 +68,14 @@ class Program { ### The Complete Code -```csharp +``` using System; class Program { static void Main() { Console.Write("Enter a number: "); int num = int.Parse(Console.ReadLine()); - + if (num > 0) { Console.WriteLine($"{num} is positive"); } else if (num < 0) { @@ -83,7 +83,7 @@ class Program { } else { Console.WriteLine("The number is zero"); } - + if (num % 2 == 0) { Console.WriteLine($"{num} is even"); } else { @@ -91,7 +91,7 @@ class Program { } } } -```csharp +``` ### What This Code Does @@ -156,46 +156,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```cs -using System; - -class Program { - static void Main() { - Console.WriteLine("Hello, World!"); - } -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard csharp conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/csharp/stage-1/level-6/lesson.md b/lessons/csharp/stage-1/level-6/lesson.md index e53df95..844e8de 100644 --- a/lessons/csharp/stage-1/level-6/lesson.md +++ b/lessons/csharp/stage-1/level-6/lesson.md @@ -23,7 +23,7 @@ Learn to repeat actions efficiently using loops. **Copy the following code EXACTLY as shown below into `main.cs`** -```csharp +``` using System; class Program { @@ -33,12 +33,12 @@ class Program { Console.Write($"{i} "); } Console.WriteLine(); - + Console.WriteLine("\nMultiplication table for 7:"); for (int i = 1; i <= 10; i++) { Console.WriteLine($"7 × {i} = {7 * i}"); } - + Console.WriteLine("\nCountdown from 5:"); int count = 5; while (count > 0) { @@ -48,7 +48,7 @@ class Program { Console.WriteLine("Liftoff!"); } } -```csharp +``` --- @@ -70,7 +70,7 @@ class Program { ### The Complete Code -```csharp +``` using System; class Program { @@ -80,12 +80,12 @@ class Program { Console.Write($"{i} "); } Console.WriteLine(); - + Console.WriteLine("\nMultiplication table for 7:"); for (int i = 1; i <= 10; i++) { Console.WriteLine($"7 × {i} = {7 * i}"); } - + Console.WriteLine("\nCountdown from 5:"); int count = 5; while (count > 0) { @@ -95,7 +95,7 @@ class Program { Console.WriteLine("Liftoff!"); } } -```csharp +``` ### What This Code Does @@ -159,46 +159,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```cs -using System; - -class Program { - static void Main() { - Console.WriteLine("Hello, World!"); - } -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard csharp conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/csharp/stage-1/level-7/lesson.md b/lessons/csharp/stage-1/level-7/lesson.md index eb58861..93f76e1 100644 --- a/lessons/csharp/stage-1/level-7/lesson.md +++ b/lessons/csharp/stage-1/level-7/lesson.md @@ -23,35 +23,35 @@ Organize your code into reusable functions/methods. **Copy the following code EXACTLY as shown below into `main.cs`** -```csharp +``` using System; class Program { static void Greet(string name) { Console.WriteLine($"Hello, {name}!"); } - + static int Add(int a, int b) { return a + b; } - + static int Factorial(int n) { if (n <= 1) return 1; return n * Factorial(n - 1); } - + static void Main() { Greet("Alice"); Greet("Bob"); - + int sum = Add(15, 7); Console.WriteLine($"15 + 7 = {sum}"); - + int fact = Factorial(5); Console.WriteLine($"5! = {fact}"); } } -```csharp +``` --- @@ -73,35 +73,35 @@ class Program { ### The Complete Code -```csharp +``` using System; class Program { static void Greet(string name) { Console.WriteLine($"Hello, {name}!"); } - + static int Add(int a, int b) { return a + b; } - + static int Factorial(int n) { if (n <= 1) return 1; return n * Factorial(n - 1); } - + static void Main() { Greet("Alice"); Greet("Bob"); - + int sum = Add(15, 7); Console.WriteLine($"15 + 7 = {sum}"); - + int fact = Factorial(5); Console.WriteLine($"5! = {fact}"); } } -```csharp +``` ### What This Code Does @@ -168,46 +168,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```cs -using System; - -class Program { - static void Main() { - Console.WriteLine("Hello, World!"); - } -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard csharp conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/csharp/stage-2/level-1/lesson.md b/lessons/csharp/stage-2/level-1/lesson.md index d5459d0..13cc21c 100644 --- a/lessons/csharp/stage-2/level-1/lesson.md +++ b/lessons/csharp/stage-2/level-1/lesson.md @@ -19,13 +19,13 @@ Now that you know the basics, it's time to think like a programmer! You'll take Here's some pseudocode that describes a simple program: -```csharp +``` START print "Welcome to the program!" print "This is my first real program" print "I'm learning to code!" END -```csharp +``` **Your mission**: Translate this pseudocode into Csharp code and save it as `main.cs`. @@ -37,18 +37,18 @@ Hints: ### How to Run -```bash +``` cd ~/.local/share/learn/workspaces/csharp/stage-2/level-1 csc main.cs -```csharp +``` Expected output: -```csharp +``` Welcome to the program! This is my first real program I'm learning to code! -```csharp +``` ### Success Checklist @@ -68,51 +68,28 @@ If you're stuck, here's what your code should look like (don't peek until you tr --- -## ANSWER KEY +## ANSWER KEY (No cheating until you've tried!) -```cs -```csharp +### Solution -(Fill in based on language-specific syntax) - -```csharp - ---- - -## What's Different About Stage 2? - -**Stage 1 (Copying):** Code was provided, you typed it -**Stage 2 (Pseudocode→Code):** Logic is provided, you write the code - -This is a crucial step! You're now writing code from specifications, not just copying. This is how real programming works. - -### Key Concepts +``` +START + print "Welcome to the program!" + print "This is my first real program" + print "I'm learning to code!" +END +``` -- Pseudocode is language-independent - the same pseudocode could translate to many languages -- Your job is to understand the logic and implement it correctly -- Different languages have different syntax, but the logic is the same +### Explanation ---- +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -## Need Help with Vim? +### Success Criteria -Remember to check the `VIM_CHEATSHEET.md` in the root directory for basic Vim commands! +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -
- -### Additional Content - -Understand the key concepts: - -- Review each function -- Understand the flow -- Learn the patterns used - -### Code Review - -Key functions and their purpose: - -- Main function: Entry point -- Helper functions: Support logic +**Great job! You've completed this lesson!** diff --git a/lessons/csharp/stage-2/level-2/lesson.md b/lessons/csharp/stage-2/level-2/lesson.md index beaec4d..2ddfa59 100644 --- a/lessons/csharp/stage-2/level-2/lesson.md +++ b/lessons/csharp/stage-2/level-2/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in C#:** -```csharp +``` ALGORITHM: Variables in Algorithms BEGIN @@ -39,7 +39,7 @@ BEGIN // Translate step by step into C# // Test with sample inputs END -```csharp +``` **Implementation Steps:** 1. Analyze what the algorithm does @@ -53,19 +53,19 @@ END ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` csc hello.cs - ```csharp + ``` 2. **Run your program**: - ```bash + ``` mono hello - ```csharp + ``` **Expected output:** -```csharp +``` Hello, World! -```csharp +``` ### How to Approach This @@ -164,7 +164,7 @@ The key is understanding what each pseudocode statement represents in C#: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```csharp +``` PSEUDOCODE: READ number IF number > 0 THEN @@ -172,7 +172,7 @@ PSEUDOCODE: ELSE PRINT "Not positive" END IF -```csharp +``` This becomes structured C# code following the language syntax. @@ -219,46 +219,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```cs -using System; - -class Program { - static void Main() { - Console.WriteLine("Hello, World!"); - } -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard csharp conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/csharp/stage-2/level-3/lesson.md b/lessons/csharp/stage-2/level-3/lesson.md index 7fac3cc..fff21f7 100644 --- a/lessons/csharp/stage-2/level-3/lesson.md +++ b/lessons/csharp/stage-2/level-3/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in C#:** -```csharp +``` ALGORITHM: Mathematical Algorithms BEGIN @@ -39,7 +39,7 @@ BEGIN // Translate step by step into C# // Test with sample inputs END -```csharp +``` **Implementation Steps:** 1. Analyze what the algorithm does @@ -53,19 +53,19 @@ END ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` csc hello.cs - ```csharp + ``` 2. **Run your program**: - ```bash + ``` mono hello - ```csharp + ``` **Expected output:** -```csharp +``` Hello, World! -```csharp +``` ### How to Approach This @@ -164,7 +164,7 @@ The key is understanding what each pseudocode statement represents in C#: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```csharp +``` PSEUDOCODE: READ number IF number > 0 THEN @@ -172,7 +172,7 @@ PSEUDOCODE: ELSE PRINT "Not positive" END IF -```csharp +``` This becomes structured C# code following the language syntax. @@ -219,46 +219,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```cs -using System; - -class Program { - static void Main() { - Console.WriteLine("Hello, World!"); - } -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard csharp conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/csharp/stage-2/level-4/lesson.md b/lessons/csharp/stage-2/level-4/lesson.md index d2b75f1..8479048 100644 --- a/lessons/csharp/stage-2/level-4/lesson.md +++ b/lessons/csharp/stage-2/level-4/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in C#:** -```csharp +``` ALGORITHM: Input/Output Algorithms BEGIN @@ -39,7 +39,7 @@ BEGIN // Translate step by step into C# // Test with sample inputs END -```csharp +``` **Implementation Steps:** 1. Analyze what the algorithm does @@ -53,19 +53,19 @@ END ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` csc hello.cs - ```csharp + ``` 2. **Run your program**: - ```bash + ``` mono hello - ```csharp + ``` **Expected output:** -```csharp +``` Hello, World! -```csharp +``` ### How to Approach This @@ -164,7 +164,7 @@ The key is understanding what each pseudocode statement represents in C#: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```csharp +``` PSEUDOCODE: READ number IF number > 0 THEN @@ -172,7 +172,7 @@ PSEUDOCODE: ELSE PRINT "Not positive" END IF -```csharp +``` This becomes structured C# code following the language syntax. @@ -219,46 +219,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```cs -using System; - -class Program { - static void Main() { - Console.WriteLine("Hello, World!"); - } -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard csharp conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/csharp/stage-2/level-5/lesson.md b/lessons/csharp/stage-2/level-5/lesson.md index de56515..74974db 100644 --- a/lessons/csharp/stage-2/level-5/lesson.md +++ b/lessons/csharp/stage-2/level-5/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in C#:** -```csharp +``` ALGORITHM: Decision Algorithms BEGIN @@ -39,7 +39,7 @@ BEGIN // Translate step by step into C# // Test with sample inputs END -```csharp +``` **Implementation Steps:** 1. Analyze what the algorithm does @@ -53,19 +53,19 @@ END ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` csc hello.cs - ```csharp + ``` 2. **Run your program**: - ```bash + ``` mono hello - ```csharp + ``` **Expected output:** -```csharp +``` Hello, World! -```csharp +``` ### How to Approach This @@ -164,7 +164,7 @@ The key is understanding what each pseudocode statement represents in C#: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```csharp +``` PSEUDOCODE: READ number IF number > 0 THEN @@ -172,7 +172,7 @@ PSEUDOCODE: ELSE PRINT "Not positive" END IF -```csharp +``` This becomes structured C# code following the language syntax. @@ -219,46 +219,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```cs -using System; - -class Program { - static void Main() { - Console.WriteLine("Hello, World!"); - } -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard csharp conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/csharp/stage-2/level-6/lesson.md b/lessons/csharp/stage-2/level-6/lesson.md index baede6f..b1db69f 100644 --- a/lessons/csharp/stage-2/level-6/lesson.md +++ b/lessons/csharp/stage-2/level-6/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in C#:** -```csharp +``` ALGORITHM: Loop Algorithms BEGIN @@ -39,7 +39,7 @@ BEGIN // Translate step by step into C# // Test with sample inputs END -```csharp +``` **Implementation Steps:** 1. Analyze what the algorithm does @@ -53,19 +53,19 @@ END ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` csc hello.cs - ```csharp + ``` 2. **Run your program**: - ```bash + ``` mono hello - ```csharp + ``` **Expected output:** -```csharp +``` Hello, World! -```csharp +``` ### How to Approach This @@ -164,7 +164,7 @@ The key is understanding what each pseudocode statement represents in C#: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```csharp +``` PSEUDOCODE: READ number IF number > 0 THEN @@ -172,7 +172,7 @@ PSEUDOCODE: ELSE PRINT "Not positive" END IF -```csharp +``` This becomes structured C# code following the language syntax. @@ -219,46 +219,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```cs -using System; - -class Program { - static void Main() { - Console.WriteLine("Hello, World!"); - } -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard csharp conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/csharp/stage-2/level-7/lesson.md b/lessons/csharp/stage-2/level-7/lesson.md index 92b59f9..e577308 100644 --- a/lessons/csharp/stage-2/level-7/lesson.md +++ b/lessons/csharp/stage-2/level-7/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in C#:** -```csharp +``` ALGORITHM: Function Design BEGIN @@ -39,7 +39,7 @@ BEGIN // Translate step by step into C# // Test with sample inputs END -```csharp +``` **Implementation Steps:** 1. Analyze what the algorithm does @@ -53,19 +53,19 @@ END ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` csc hello.cs - ```csharp + ``` 2. **Run your program**: - ```bash + ``` mono hello - ```csharp + ``` **Expected output:** -```csharp +``` Hello, World! -```csharp +``` ### How to Approach This @@ -164,7 +164,7 @@ The key is understanding what each pseudocode statement represents in C#: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```csharp +``` PSEUDOCODE: READ number IF number > 0 THEN @@ -172,7 +172,7 @@ PSEUDOCODE: ELSE PRINT "Not positive" END IF -```csharp +``` This becomes structured C# code following the language syntax. @@ -219,46 +219,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```cs -using System; - -class Program { - static void Main() { - Console.WriteLine("Hello, World!"); - } -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard csharp conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/csharp/stage-3/level-1/lesson.md b/lessons/csharp/stage-3/level-1/lesson.md index 0ecf3bd..fec7aef 100644 --- a/lessons/csharp/stage-3/level-1/lesson.md +++ b/lessons/csharp/stage-3/level-1/lesson.md @@ -21,13 +21,13 @@ You're now ready for Stage 3! This is where you start thinking like a real progr Step 1: Write the pseudocode first -```csharp +``` What should happen: 1. Print "Hello, [name]" Write your pseudocode in plain English below: (Your pseudocode here) -```csharp +``` Step 2: Implement your pseudocode in Csharp @@ -36,19 +36,19 @@ Create `main.csharp.csharp` with your solution. ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` csc hello.cs - ```csharp + ``` 2. **Run your program**: - ```bash + ``` mono hello - ```csharp + ``` **Expected output:** -```csharp +``` Hello, World! -```csharp +``` ### Success Checklist @@ -90,82 +90,26 @@ Check the `VIM_CHEATSHEET.md` for basic Vim commands! ## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown - -### Key Concepts - -- Review the code structure specific to Csharp -- Understand the execution flow -- Learn common pitfalls and solutions - -### Next Steps - -Practice the code and experiment with variations! - ---- - -**Congratulations! Keep coding!** - -### How to Run - -1. Open the code file -2. Review and understand the implementation -3. Execute using: `r` in Vim - -### Additional Content - -Understand the key concepts: - -- Review each function -- Understand the flow -- Learn the patterns used - -### Code Review - -Key functions and their purpose: - -- Main function: Entry point -- Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```cs -using System; - -class Program { - static void Main() { - Console.WriteLine("Hello, World!"); - } -} +### Solution ``` +What should happen: +1. Print "Hello, [name]" -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: +Write your pseudocode in plain English below: +(Your pseudocode here) +``` -1. **Structure**: The program follows standard csharp conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions +### Explanation -### Testing Your Solution +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -Try these test cases to verify your code works correctly: +### Success Criteria -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does -### Tips for Understanding +--- -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs +**Great job! You've completed this lesson!** diff --git a/lessons/csharp/stage-3/level-2/lesson.md b/lessons/csharp/stage-3/level-2/lesson.md index 0abcdec..6ec6731 100644 --- a/lessons/csharp/stage-3/level-2/lesson.md +++ b/lessons/csharp/stage-3/level-2/lesson.md @@ -50,19 +50,19 @@ Data Structure Planning - Design an algorithm to solve this problem, then implem ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` csc hello.cs - ```csharp + ``` 2. **Run your program**: - ```bash + ``` mono hello - ```csharp + ``` **Expected output:** -```csharp +``` Hello, World! -```csharp +``` ### How to Approach This @@ -159,7 +159,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```csharp +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -173,7 +173,7 @@ BEGIN - Step 3 4. Display results END -```csharp +``` Then translate this directly to C# code. @@ -220,46 +220,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```cs -using System; - -class Program { - static void Main() { - Console.WriteLine("Hello, World!"); - } -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard csharp conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/csharp/stage-3/level-3/lesson.md b/lessons/csharp/stage-3/level-3/lesson.md index 18207a4..3b10442 100644 --- a/lessons/csharp/stage-3/level-3/lesson.md +++ b/lessons/csharp/stage-3/level-3/lesson.md @@ -50,19 +50,19 @@ Mathematical Problems - Design an algorithm to solve this problem, then implemen ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` csc hello.cs - ```csharp + ``` 2. **Run your program**: - ```bash + ``` mono hello - ```csharp + ``` **Expected output:** -```csharp +``` Hello, World! -```csharp +``` ### How to Approach This @@ -159,7 +159,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```csharp +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -173,7 +173,7 @@ BEGIN - Step 3 4. Display results END -```csharp +``` Then translate this directly to C# code. @@ -220,46 +220,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```cs -using System; - -class Program { - static void Main() { - Console.WriteLine("Hello, World!"); - } -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard csharp conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/csharp/stage-3/level-4/lesson.md b/lessons/csharp/stage-3/level-4/lesson.md index d56c2cd..3b6e956 100644 --- a/lessons/csharp/stage-3/level-4/lesson.md +++ b/lessons/csharp/stage-3/level-4/lesson.md @@ -50,19 +50,19 @@ Text Processing Problems - Design an algorithm to solve this problem, then imple ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` csc hello.cs - ```csharp + ``` 2. **Run your program**: - ```bash + ``` mono hello - ```csharp + ``` **Expected output:** -```csharp +``` Hello, World! -```csharp +``` ### How to Approach This @@ -159,7 +159,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```csharp +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -173,7 +173,7 @@ BEGIN - Step 3 4. Display results END -```csharp +``` Then translate this directly to C# code. @@ -220,46 +220,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```cs -using System; - -class Program { - static void Main() { - Console.WriteLine("Hello, World!"); - } -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard csharp conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/csharp/stage-3/level-5/lesson.md b/lessons/csharp/stage-3/level-5/lesson.md index fe65529..f920771 100644 --- a/lessons/csharp/stage-3/level-5/lesson.md +++ b/lessons/csharp/stage-3/level-5/lesson.md @@ -50,19 +50,19 @@ Logic Problems - Design an algorithm to solve this problem, then implement it. ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` csc hello.cs - ```csharp + ``` 2. **Run your program**: - ```bash + ``` mono hello - ```csharp + ``` **Expected output:** -```csharp +``` Hello, World! -```csharp +``` ### How to Approach This @@ -159,7 +159,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```csharp +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -173,7 +173,7 @@ BEGIN - Step 3 4. Display results END -```csharp +``` Then translate this directly to C# code. @@ -220,46 +220,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```cs -using System; - -class Program { - static void Main() { - Console.WriteLine("Hello, World!"); - } -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard csharp conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/csharp/stage-3/level-6/lesson.md b/lessons/csharp/stage-3/level-6/lesson.md index 69f74a5..4b65ba5 100644 --- a/lessons/csharp/stage-3/level-6/lesson.md +++ b/lessons/csharp/stage-3/level-6/lesson.md @@ -50,19 +50,19 @@ Search Algorithms - Design an algorithm to solve this problem, then implement it ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` csc hello.cs - ```csharp + ``` 2. **Run your program**: - ```bash + ``` mono hello - ```csharp + ``` **Expected output:** -```csharp +``` Hello, World! -```csharp +``` ### How to Approach This @@ -159,7 +159,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```csharp +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -173,7 +173,7 @@ BEGIN - Step 3 4. Display results END -```csharp +``` Then translate this directly to C# code. @@ -220,46 +220,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```cs -using System; - -class Program { - static void Main() { - Console.WriteLine("Hello, World!"); - } -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard csharp conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/csharp/stage-3/level-7/lesson.md b/lessons/csharp/stage-3/level-7/lesson.md index b63ac83..683a14d 100644 --- a/lessons/csharp/stage-3/level-7/lesson.md +++ b/lessons/csharp/stage-3/level-7/lesson.md @@ -50,19 +50,19 @@ Sorting Algorithms - Design an algorithm to solve this problem, then implement i ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` csc hello.cs - ```csharp + ``` 2. **Run your program**: - ```bash + ``` mono hello - ```csharp + ``` **Expected output:** -```csharp +``` Hello, World! -```csharp +``` ### How to Approach This @@ -159,7 +159,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```csharp +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -173,7 +173,7 @@ BEGIN - Step 3 4. Display results END -```csharp +``` Then translate this directly to C# code. @@ -220,46 +220,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```cs -using System; - -class Program { - static void Main() { - Console.WriteLine("Hello, World!"); - } -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard csharp conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/csharp/stage-4/level-1/lesson.md b/lessons/csharp/stage-4/level-1/lesson.md index e801f35..5f4d225 100644 --- a/lessons/csharp/stage-4/level-1/lesson.md +++ b/lessons/csharp/stage-4/level-1/lesson.md @@ -28,19 +28,19 @@ Requirements: ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` csc hello.cs - ```csharp + ``` 2. **Run your program**: - ```bash + ``` mono hello - ```csharp + ``` **Expected output:** -```csharp +``` Hello, World! -```csharp +``` ### How to Approach This @@ -119,46 +119,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```cs -using System; - -class Program { - static void Main() { - Console.WriteLine("Hello, World!"); - } -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard csharp conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/csharp/stage-4/level-2/lesson.md b/lessons/csharp/stage-4/level-2/lesson.md index 499c5fe..5c3c202 100644 --- a/lessons/csharp/stage-4/level-2/lesson.md +++ b/lessons/csharp/stage-4/level-2/lesson.md @@ -50,19 +50,19 @@ Build a complete Text Analysis Tool application that: ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` csc hello.cs - ```csharp + ``` 2. **Run your program**: - ```bash + ``` mono hello - ```csharp + ``` **Expected output:** -```csharp +``` Hello, World! -```csharp +``` ### How to Approach This @@ -162,13 +162,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```csharp +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```csharp +``` Build incrementally - get one feature working before adding the next. @@ -215,46 +215,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```cs -using System; - -class Program { - static void Main() { - Console.WriteLine("Hello, World!"); - } -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard csharp conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/csharp/stage-4/level-3/lesson.md b/lessons/csharp/stage-4/level-3/lesson.md index 8e47fb2..776ef20 100644 --- a/lessons/csharp/stage-4/level-3/lesson.md +++ b/lessons/csharp/stage-4/level-3/lesson.md @@ -50,19 +50,19 @@ Build a complete Data Processing application that: ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` csc hello.cs - ```csharp + ``` 2. **Run your program**: - ```bash + ``` mono hello - ```csharp + ``` **Expected output:** -```csharp +``` Hello, World! -```csharp +``` ### How to Approach This @@ -162,13 +162,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```csharp +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```csharp +``` Build incrementally - get one feature working before adding the next. @@ -215,46 +215,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```cs -using System; - -class Program { - static void Main() { - Console.WriteLine("Hello, World!"); - } -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard csharp conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/csharp/stage-4/level-4/lesson.md b/lessons/csharp/stage-4/level-4/lesson.md index 02ebd31..16e0703 100644 --- a/lessons/csharp/stage-4/level-4/lesson.md +++ b/lessons/csharp/stage-4/level-4/lesson.md @@ -50,19 +50,19 @@ Build a complete File Operations application that: ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` csc hello.cs - ```csharp + ``` 2. **Run your program**: - ```bash + ``` mono hello - ```csharp + ``` **Expected output:** -```csharp +``` Hello, World! -```csharp +``` ### How to Approach This @@ -162,13 +162,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```csharp +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```csharp +``` Build incrementally - get one feature working before adding the next. @@ -215,46 +215,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```cs -using System; - -class Program { - static void Main() { - Console.WriteLine("Hello, World!"); - } -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard csharp conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/csharp/stage-4/level-5/lesson.md b/lessons/csharp/stage-4/level-5/lesson.md index 38ae8ab..19ca840 100644 --- a/lessons/csharp/stage-4/level-5/lesson.md +++ b/lessons/csharp/stage-4/level-5/lesson.md @@ -50,19 +50,19 @@ Build a complete API Integration application that: ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` csc hello.cs - ```csharp + ``` 2. **Run your program**: - ```bash + ``` mono hello - ```csharp + ``` **Expected output:** -```csharp +``` Hello, World! -```csharp +``` ### How to Approach This @@ -162,13 +162,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```csharp +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```csharp +``` Build incrementally - get one feature working before adding the next. @@ -215,46 +215,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```cs -using System; - -class Program { - static void Main() { - Console.WriteLine("Hello, World!"); - } -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard csharp conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/csharp/stage-4/level-6/lesson.md b/lessons/csharp/stage-4/level-6/lesson.md index 4d26f07..c32be63 100644 --- a/lessons/csharp/stage-4/level-6/lesson.md +++ b/lessons/csharp/stage-4/level-6/lesson.md @@ -50,19 +50,19 @@ Build a complete Database Operations application that: ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` csc hello.cs - ```csharp + ``` 2. **Run your program**: - ```bash + ``` mono hello - ```csharp + ``` **Expected output:** -```csharp +``` Hello, World! -```csharp +``` ### How to Approach This @@ -162,13 +162,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```csharp +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```csharp +``` Build incrementally - get one feature working before adding the next. @@ -215,46 +215,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```cs -using System; - -class Program { - static void Main() { - Console.WriteLine("Hello, World!"); - } -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard csharp conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/csharp/stage-4/level-7/lesson.md b/lessons/csharp/stage-4/level-7/lesson.md index 28aeb5c..1d063b4 100644 --- a/lessons/csharp/stage-4/level-7/lesson.md +++ b/lessons/csharp/stage-4/level-7/lesson.md @@ -50,19 +50,19 @@ Build a complete Complete Application application that: ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` csc hello.cs - ```csharp + ``` 2. **Run your program**: - ```bash + ``` mono hello - ```csharp + ``` **Expected output:** -```csharp +``` Hello, World! -```csharp +``` ### How to Approach This @@ -162,13 +162,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```csharp +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```csharp +``` Build incrementally - get one feature working before adding the next. @@ -215,46 +215,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```cs -using System; - -class Program { - static void Main() { - Console.WriteLine("Hello, World!"); - } -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard csharp conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/csharp/stage-5/level-1/lesson.md b/lessons/csharp/stage-5/level-1/lesson.md index 0dc0d08..6fa1072 100644 --- a/lessons/csharp/stage-5/level-1/lesson.md +++ b/lessons/csharp/stage-5/level-1/lesson.md @@ -28,19 +28,19 @@ You're going to build a complete Csharp application. This is a real project that ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` csc hello.cs - ```csharp + ``` 2. **Run your program**: - ```bash + ``` mono hello - ```csharp + ``` **Expected output:** -```csharp +``` Hello, World! -```csharp +``` ### Project Requirements @@ -159,46 +159,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```cs -using System; - -class Program { - static void Main() { - Console.WriteLine("Hello, World!"); - } -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard csharp conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/csharp/stage-5/level-2/lesson.md b/lessons/csharp/stage-5/level-2/lesson.md index 02d57bd..2d57fe3 100644 --- a/lessons/csharp/stage-5/level-2/lesson.md +++ b/lessons/csharp/stage-5/level-2/lesson.md @@ -57,19 +57,19 @@ Create a production-ready CLI Tool using C# with: ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` csc hello.cs - ```csharp + ``` 2. **Run your program**: - ```bash + ``` mono hello - ```csharp + ``` **Expected output:** -```csharp +``` Hello, World! -```csharp +``` ### How to Approach This @@ -230,46 +230,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```cs -using System; - -class Program { - static void Main() { - Console.WriteLine("Hello, World!"); - } -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard csharp conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/csharp/stage-5/level-3/lesson.md b/lessons/csharp/stage-5/level-3/lesson.md index 900ba88..de20797 100644 --- a/lessons/csharp/stage-5/level-3/lesson.md +++ b/lessons/csharp/stage-5/level-3/lesson.md @@ -57,19 +57,19 @@ Create a production-ready REST API using C# with: ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` csc hello.cs - ```csharp + ``` 2. **Run your program**: - ```bash + ``` mono hello - ```csharp + ``` **Expected output:** -```csharp +``` Hello, World! -```csharp +``` ### How to Approach This @@ -230,46 +230,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```cs -using System; - -class Program { - static void Main() { - Console.WriteLine("Hello, World!"); - } -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard csharp conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/csharp/stage-5/level-4/lesson.md b/lessons/csharp/stage-5/level-4/lesson.md index 58210a1..bf6db76 100644 --- a/lessons/csharp/stage-5/level-4/lesson.md +++ b/lessons/csharp/stage-5/level-4/lesson.md @@ -57,19 +57,19 @@ Create a production-ready Data Visualization using C# with: ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` csc hello.cs - ```csharp + ``` 2. **Run your program**: - ```bash + ``` mono hello - ```csharp + ``` **Expected output:** -```csharp +``` Hello, World! -```csharp +``` ### How to Approach This @@ -230,46 +230,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```cs -using System; - -class Program { - static void Main() { - Console.WriteLine("Hello, World!"); - } -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard csharp conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/csharp/stage-5/level-5/lesson.md b/lessons/csharp/stage-5/level-5/lesson.md index ccbaeaa..a1209da 100644 --- a/lessons/csharp/stage-5/level-5/lesson.md +++ b/lessons/csharp/stage-5/level-5/lesson.md @@ -57,19 +57,19 @@ Create a production-ready Automated Testing using C# with: ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` csc hello.cs - ```csharp + ``` 2. **Run your program**: - ```bash + ``` mono hello - ```csharp + ``` **Expected output:** -```csharp +``` Hello, World! -```csharp +``` ### How to Approach This @@ -230,46 +230,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```cs -using System; - -class Program { - static void Main() { - Console.WriteLine("Hello, World!"); - } -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard csharp conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/csharp/stage-5/level-6/lesson.md b/lessons/csharp/stage-5/level-6/lesson.md index cd8fedf..51c0e76 100644 --- a/lessons/csharp/stage-5/level-6/lesson.md +++ b/lessons/csharp/stage-5/level-6/lesson.md @@ -57,19 +57,19 @@ Create a production-ready Performance Optimization using C# with: ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` csc hello.cs - ```csharp + ``` 2. **Run your program**: - ```bash + ``` mono hello - ```csharp + ``` **Expected output:** -```csharp +``` Hello, World! -```csharp +``` ### How to Approach This @@ -230,46 +230,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```cs -using System; - -class Program { - static void Main() { - Console.WriteLine("Hello, World!"); - } -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard csharp conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/csharp/stage-5/level-7/lesson.md b/lessons/csharp/stage-5/level-7/lesson.md index ae9428f..6a7ba1e 100644 --- a/lessons/csharp/stage-5/level-7/lesson.md +++ b/lessons/csharp/stage-5/level-7/lesson.md @@ -57,19 +57,19 @@ Create a production-ready Final Capstone Project using C# with: ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` csc hello.cs - ```csharp + ``` 2. **Run your program**: - ```bash + ``` mono hello - ```csharp + ``` **Expected output:** -```csharp +``` Hello, World! -```csharp +``` ### How to Approach This @@ -230,46 +230,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```cs -using System; - -class Program { - static void Main() { - Console.WriteLine("Hello, World!"); - } -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard csharp conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/dart/stage-1/level-1/lesson.md b/lessons/dart/stage-1/level-1/lesson.md index f8b3194..94e9421 100644 --- a/lessons/dart/stage-1/level-1/lesson.md +++ b/lessons/dart/stage-1/level-1/lesson.md @@ -21,23 +21,23 @@ Welcome to Dart! Today, you'll create your first Dart program. Dart is a modern Copy the following code EXACTLY as shown into a new file called `hello.dart`: -```dart +``` void main() { print("Hello, World!"); } -```dart +``` ### How to Execute -```bash +``` dart hello.dart -```dart +``` Expected output: -```dart +``` Hello, World! -```dart +``` ### Success Checklist @@ -60,24 +60,24 @@ Hello, World! ### The Complete Solution -```dart +``` void main() { print("Hello, World!"); } -```dart +``` ### Code Breakdown ```c # include -```dart +``` - **`#include`** = A preprocessor command that includes libraries - **``** = Standard Input/Output library - gives us printf() - **Purpose**: Lets us use functions like printf() for printing ```c main function { -```dart +``` - **`int`** = Return type - this function will return an integer - **`main`** = Function name - every C program starts here - **`()`** = Parameters (empty means no inputs needed) @@ -85,7 +85,7 @@ main function { ```c printf("Hello, World!\n"); -```dart +``` - **`printf`** = "print formatted" function from stdio.h - **`"`** = String literal start/end - **`\n`** = Escape sequence for newline (moves cursor to next line) @@ -94,7 +94,7 @@ main function { ```c return 0; } -```dart +``` - **`return 0`** = Returns 0 to indicate successful execution - **`}`** = Closing brace - end of function body @@ -146,42 +146,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```dart -void main() { - print("Hello, World!"); -} - -```dart - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard dart conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/dart/stage-1/level-2/lesson.md b/lessons/dart/stage-1/level-2/lesson.md index bebb454..5f82276 100644 --- a/lessons/dart/stage-1/level-2/lesson.md +++ b/lessons/dart/stage-1/level-2/lesson.md @@ -20,7 +20,7 @@ Now that you know how to run Dart programs, let's learn about variables! Variabl Copy the following code EXACTLY as shown into a new file called `variables.dart`: -```dart +``` void main() { String name = "Alice"; int age = 25; @@ -32,22 +32,22 @@ void main() { print("Your height is $height feet."); print("Student status: $isStudent"); } -```dart +``` ### How to Execute -```bash +``` dart variables.dart -```dart +``` Expected output: -```dart +``` Hello, Alice! You are 25 years old. Your height is 5.6 feet. Student status: true -```dart +``` ### Success Checklist @@ -87,82 +87,32 @@ Remember to check the `VIM_CHEATSHEET.md` in the root directory for basic Vim co ## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -### Key Concepts - -- Review the code structure specific to Dart -- Understand the execution flow -- Learn common pitfalls and solutions - -### Next Steps - -Practice the code and experiment with variations! - ---- - -**Congratulations! Keep coding!** - - - -### How to Run - -1. Open the code file -2. Review and understand the implementation -3. Execute using: `r` in Vim - - -### Additional Content - -Understand the key concepts: - -- Review each function -- Understand the flow -- Learn the patterns used - - -### Code Review - -Key functions and their purpose: - -- Main function: Entry point -- Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```dart +``` void main() { - print("Hello, World!"); -} - -```dart - -### Code Breakdown + String name = "Alice"; + int age = 25; + double height = 5.6; + bool isStudent = true; -This solution demonstrates the key concepts from this lesson: + print("Hello, $name!"); + print("You are $age years old."); + print("Your height is $height feet."); + print("Student status: $isStudent"); +} +``` -1. **Structure**: The program follows standard dart conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions +### Explanation -### Testing Your Solution +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -Try these test cases to verify your code works correctly: +### Success Criteria -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does -### Tips for Understanding +--- -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs +**Great job! You've completed this lesson!** diff --git a/lessons/dart/stage-1/level-3/lesson.md b/lessons/dart/stage-1/level-3/lesson.md index 72bcd81..c98d2d1 100644 --- a/lessons/dart/stage-1/level-3/lesson.md +++ b/lessons/dart/stage-1/level-3/lesson.md @@ -23,11 +23,11 @@ Master arithmetic operations and use the language as your calculator. **Copy the following code EXACTLY as shown below into `main.dart`** -```dart +``` void main() { int a = 15; int b = 4; - + print('Addition: $a + $b = ${a + b}'); print('Subtraction: $a - $b = ${a - b}'); print('Multiplication: $a × $b = ${a * b}'); @@ -35,7 +35,7 @@ void main() { print('Integer Division: $a ~/ $b = ${a ~/ b}'); print('Remainder: $a % $b = ${a % b}'); } -```dart +``` --- @@ -57,11 +57,11 @@ void main() { ### The Complete Code -```dart +``` void main() { int a = 15; int b = 4; - + print('Addition: $a + $b = ${a + b}'); print('Subtraction: $a - $b = ${a - b}'); print('Multiplication: $a × $b = ${a * b}'); @@ -69,7 +69,7 @@ void main() { print('Integer Division: $a ~/ $b = ${a ~/ b}'); print('Remainder: $a % $b = ${a % b}'); } -```dart +``` ### What This Code Does @@ -138,42 +138,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```dart -void main() { - print("Hello, World!"); -} - -```dart - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard dart conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/dart/stage-1/level-4/lesson.md b/lessons/dart/stage-1/level-4/lesson.md index b36ee2d..3407e2a 100644 --- a/lessons/dart/stage-1/level-4/lesson.md +++ b/lessons/dart/stage-1/level-4/lesson.md @@ -23,21 +23,21 @@ Make your programs interactive by reading input from users. **Copy the following code EXACTLY as shown below into `main.dart`** -```dart +``` import 'dart:io'; void main() { stdout.write('Enter your name: '); String? name = stdin.readLineSync(); - + stdout.write('Enter your age: '); int age = int.parse(stdin.readLineSync()!); - + print('Hello, $name!'); print('You are $age years old.'); print('Next year you\'ll be ${age + 1}.'); } -```dart +``` --- @@ -59,21 +59,21 @@ void main() { ### The Complete Code -```dart +``` import 'dart:io'; void main() { stdout.write('Enter your name: '); String? name = stdin.readLineSync(); - + stdout.write('Enter your age: '); int age = int.parse(stdin.readLineSync()!); - + print('Hello, $name!'); print('You are $age years old.'); print('Next year you\'ll be ${age + 1}.'); } -```dart +``` ### What This Code Does @@ -142,42 +142,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```dart -void main() { - print("Hello, World!"); -} - -```dart - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard dart conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/dart/stage-1/level-5/lesson.md b/lessons/dart/stage-1/level-5/lesson.md index 622a872..8bf3ee3 100644 --- a/lessons/dart/stage-1/level-5/lesson.md +++ b/lessons/dart/stage-1/level-5/lesson.md @@ -23,13 +23,13 @@ Add decision-making to your programs with if/else statements. **Copy the following code EXACTLY as shown below into `main.dart`** -```dart +``` import 'dart:io'; void main() { stdout.write('Enter a number: '); int num = int.parse(stdin.readLineSync()!); - + if (num > 0) { print('$num is positive'); } else if (num < 0) { @@ -37,14 +37,14 @@ void main() { } else { print('The number is zero'); } - + if (num % 2 == 0) { print('$num is even'); } else { print('$num is odd'); } } -```dart +``` --- @@ -66,13 +66,13 @@ void main() { ### The Complete Code -```dart +``` import 'dart:io'; void main() { stdout.write('Enter a number: '); int num = int.parse(stdin.readLineSync()!); - + if (num > 0) { print('$num is positive'); } else if (num < 0) { @@ -80,14 +80,14 @@ void main() { } else { print('The number is zero'); } - + if (num % 2 == 0) { print('$num is even'); } else { print('$num is odd'); } } -```dart +``` ### What This Code Does @@ -154,42 +154,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```dart -void main() { - print("Hello, World!"); -} - -```dart - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard dart conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/dart/stage-1/level-6/lesson.md b/lessons/dart/stage-1/level-6/lesson.md index cad307f..5be0138 100644 --- a/lessons/dart/stage-1/level-6/lesson.md +++ b/lessons/dart/stage-1/level-6/lesson.md @@ -23,19 +23,19 @@ Learn to repeat actions efficiently using loops. **Copy the following code EXACTLY as shown below into `main.dart`** -```dart +``` void main() { print('Counting 1 to 10:'); for (int i = 1; i <= 10; i++) { stdout.write('$i '); } print(''); - + print('\nMultiplication table for 7:'); for (int i = 1; i <= 10; i++) { print('7 × $i = ${7 * i}'); } - + print('\nCountdown from 5:'); int count = 5; while (count > 0) { @@ -44,7 +44,7 @@ void main() { } print('Liftoff!'); } -```dart +``` --- @@ -66,19 +66,19 @@ void main() { ### The Complete Code -```dart +``` void main() { print('Counting 1 to 10:'); for (int i = 1; i <= 10; i++) { stdout.write('$i '); } print(''); - + print('\nMultiplication table for 7:'); for (int i = 1; i <= 10; i++) { print('7 × $i = ${7 * i}'); } - + print('\nCountdown from 5:'); int count = 5; while (count > 0) { @@ -87,7 +87,7 @@ void main() { } print('Liftoff!'); } -```dart +``` ### What This Code Does @@ -153,42 +153,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```dart -void main() { - print("Hello, World!"); -} - -```dart - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard dart conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/dart/stage-1/level-7/lesson.md b/lessons/dart/stage-1/level-7/lesson.md index 953a39e..7a44fbe 100644 --- a/lessons/dart/stage-1/level-7/lesson.md +++ b/lessons/dart/stage-1/level-7/lesson.md @@ -23,7 +23,7 @@ Organize your code into reusable functions/methods. **Copy the following code EXACTLY as shown below into `main.dart`** -```dart +``` void greet(String name) { print('Hello, $name!'); } @@ -40,14 +40,14 @@ int factorial(int n) { void main() { greet('Alice'); greet('Bob'); - + int sum = add(15, 7); print('15 + 7 = $sum'); - + int fact = factorial(5); print('5! = $fact'); } -```dart +``` --- @@ -69,7 +69,7 @@ void main() { ### The Complete Code -```dart +``` void greet(String name) { print('Hello, $name!'); } @@ -86,14 +86,14 @@ int factorial(int n) { void main() { greet('Alice'); greet('Bob'); - + int sum = add(15, 7); print('15 + 7 = $sum'); - + int fact = factorial(5); print('5! = $fact'); } -```dart +``` ### What This Code Does @@ -162,42 +162,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```dart -void main() { - print("Hello, World!"); -} - -```dart - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard dart conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/dart/stage-2/level-1/lesson.md b/lessons/dart/stage-2/level-1/lesson.md index 229c898..b8d3bd6 100644 --- a/lessons/dart/stage-2/level-1/lesson.md +++ b/lessons/dart/stage-2/level-1/lesson.md @@ -20,13 +20,13 @@ Now that you know the basics, it's time to think like a programmer! You'll take Here's some pseudocode that describes a simple program: -```dart +``` START print "Welcome to the program!" print "This is my first real program" print "I'm learning to code!" END -```dart +``` **Your mission**: Translate this pseudocode into Dart code and save it as `main.dart`. @@ -42,18 +42,18 @@ Hints: ### How to Run -```bash +``` cd ~/.local/share/learn/workspaces/dart/stage-2/level-1 dart main.dart -```dart +``` Expected output: -```dart +``` Welcome to the program! This is my first real program I'm learning to code! -```dart +``` ### Success Checklist @@ -73,53 +73,28 @@ If you're stuck, here's what your code should look like (don't peek until you tr --- -## ANSWER KEY +## ANSWER KEY (No cheating until you've tried!) -```dart -```dart +### Solution -(Fill in based on language-specific syntax) - -```dart - ---- - -## What's Different About Stage 2? - -**Stage 1 (Copying):** Code was provided, you typed it -**Stage 2 (Pseudocode→Code):** Logic is provided, you write the code - -This is a crucial step! You're now writing code from specifications, not just copying. This is how real programming works. - -### Key Concepts +``` +START + print "Welcome to the program!" + print "This is my first real program" + print "I'm learning to code!" +END +``` -- Pseudocode is language-independent - the same pseudocode could translate to many languages -- Your job is to understand the logic and implement it correctly -- Different languages have different syntax, but the logic is the same +### Explanation ---- +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -## Need Help with Vim? +### Success Criteria -Remember to check the `VIM_CHEATSHEET.md` in the root directory for basic Vim commands! +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -
- - -### Additional Content - -Understand the key concepts: - -- Review each function -- Understand the flow -- Learn the patterns used - - -### Code Review - -Key functions and their purpose: - -- Main function: Entry point -- Helper functions: Support logic +**Great job! You've completed this lesson!** diff --git a/lessons/dart/stage-2/level-2/lesson.md b/lessons/dart/stage-2/level-2/lesson.md index 1a82e3b..2281407 100644 --- a/lessons/dart/stage-2/level-2/lesson.md +++ b/lessons/dart/stage-2/level-2/lesson.md @@ -20,24 +20,24 @@ You're progressing! Now you'll take more complex pseudocode and translate it int Here's some pseudocode: -```dart +``` [Pseudocode will be specific to the level] -```dart +``` **Your mission**: Translate this into Dart code in `main.dart.dart`. ### How to Run -```bash +``` cd ~/.local/share/learn/workspaces/dart/stage-2/level-2 -```dart +``` Then run your program. **Expected output:** -```dart +``` (Output will vary based on your implementation) -```dart +``` ### Success Checklist @@ -71,75 +71,22 @@ Check the `VIM_CHEATSHEET.md` for basic Vim commands! ## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -### Key Concepts - -- Review the code structure specific to Dart -- Understand the execution flow -- Learn common pitfalls and solutions - -### Next Steps - -Practice the code and experiment with variations! - ---- - -**Congratulations! Keep coding!** - - - -### Additional Content - -Understand the key concepts: - -- Review each function -- Understand the flow -- Learn the patterns used - - -### Code Review - -Key functions and their purpose: - -- Main function: Entry point -- Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```dart -void main() { - print("Hello, World!"); -} - -```dart - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: +``` +[Pseudocode will be specific to the level] +``` -1. **Structure**: The program follows standard dart conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions +### Explanation -### Testing Your Solution +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -Try these test cases to verify your code works correctly: +### Success Criteria -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does -### Tips for Understanding +--- -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs +**Great job! You've completed this lesson!** diff --git a/lessons/dart/stage-2/level-3/lesson.md b/lessons/dart/stage-2/level-3/lesson.md index a5c9150..fc0c8b2 100644 --- a/lessons/dart/stage-2/level-3/lesson.md +++ b/lessons/dart/stage-2/level-3/lesson.md @@ -20,24 +20,24 @@ You're progressing! Now you'll take more complex pseudocode and translate it int Here's some pseudocode: -```dart +``` [Pseudocode will be specific to the level] -```dart +``` **Your mission**: Translate this into Dart code in `main.dart.dart`. ### How to Run -```bash +``` cd ~/.local/share/learn/workspaces/dart/stage-2/level-3 -```dart +``` Then run your program. **Expected output:** -```dart +``` (Output will vary based on your implementation) -```dart +``` ### Success Checklist @@ -71,75 +71,22 @@ Check the `VIM_CHEATSHEET.md` for basic Vim commands! ## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -### Key Concepts - -- Review the code structure specific to Dart -- Understand the execution flow -- Learn common pitfalls and solutions - -### Next Steps - -Practice the code and experiment with variations! - ---- - -**Congratulations! Keep coding!** - - - -### Additional Content - -Understand the key concepts: - -- Review each function -- Understand the flow -- Learn the patterns used - - -### Code Review - -Key functions and their purpose: - -- Main function: Entry point -- Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```dart -void main() { - print("Hello, World!"); -} - -```dart - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: +``` +[Pseudocode will be specific to the level] +``` -1. **Structure**: The program follows standard dart conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions +### Explanation -### Testing Your Solution +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -Try these test cases to verify your code works correctly: +### Success Criteria -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does -### Tips for Understanding +--- -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs +**Great job! You've completed this lesson!** diff --git a/lessons/dart/stage-2/level-4/lesson.md b/lessons/dart/stage-2/level-4/lesson.md index d86c58c..292094d 100644 --- a/lessons/dart/stage-2/level-4/lesson.md +++ b/lessons/dart/stage-2/level-4/lesson.md @@ -20,24 +20,24 @@ You're progressing! Now you'll take more complex pseudocode and translate it int Here's some pseudocode: -```dart +``` [Pseudocode will be specific to the level] -```dart +``` **Your mission**: Translate this into Dart code in `main.dart.dart`. ### How to Run -```bash +``` cd ~/.local/share/learn/workspaces/dart/stage-2/level-4 -```dart +``` Then run your program. **Expected output:** -```dart +``` (Output will vary based on your implementation) -```dart +``` ### Success Checklist @@ -71,75 +71,22 @@ Check the `VIM_CHEATSHEET.md` for basic Vim commands! ## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -### Key Concepts - -- Review the code structure specific to Dart -- Understand the execution flow -- Learn common pitfalls and solutions - -### Next Steps - -Practice the code and experiment with variations! - ---- - -**Congratulations! Keep coding!** - - - -### Additional Content - -Understand the key concepts: - -- Review each function -- Understand the flow -- Learn the patterns used - - -### Code Review - -Key functions and their purpose: - -- Main function: Entry point -- Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```dart -void main() { - print("Hello, World!"); -} - -```dart - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: +``` +[Pseudocode will be specific to the level] +``` -1. **Structure**: The program follows standard dart conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions +### Explanation -### Testing Your Solution +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -Try these test cases to verify your code works correctly: +### Success Criteria -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does -### Tips for Understanding +--- -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs +**Great job! You've completed this lesson!** diff --git a/lessons/dart/stage-2/level-5/lesson.md b/lessons/dart/stage-2/level-5/lesson.md index 228d7ce..752f2e8 100644 --- a/lessons/dart/stage-2/level-5/lesson.md +++ b/lessons/dart/stage-2/level-5/lesson.md @@ -20,24 +20,24 @@ You're progressing! Now you'll take more complex pseudocode and translate it int Here's some pseudocode: -```dart +``` [Pseudocode will be specific to the level] -```dart +``` **Your mission**: Translate this into Dart code in `main.dart.dart`. ### How to Run -```bash +``` cd ~/.local/share/learn/workspaces/dart/stage-2/level-5 -```dart +``` Then run your program. **Expected output:** -```dart +``` (Output will vary based on your implementation) -```dart +``` ### Success Checklist @@ -71,75 +71,22 @@ Check the `VIM_CHEATSHEET.md` for basic Vim commands! ## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -### Key Concepts - -- Review the code structure specific to Dart -- Understand the execution flow -- Learn common pitfalls and solutions - -### Next Steps - -Practice the code and experiment with variations! - ---- - -**Congratulations! Keep coding!** - - - -### Additional Content - -Understand the key concepts: - -- Review each function -- Understand the flow -- Learn the patterns used - - -### Code Review - -Key functions and their purpose: - -- Main function: Entry point -- Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```dart -void main() { - print("Hello, World!"); -} - -```dart - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: +``` +[Pseudocode will be specific to the level] +``` -1. **Structure**: The program follows standard dart conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions +### Explanation -### Testing Your Solution +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -Try these test cases to verify your code works correctly: +### Success Criteria -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does -### Tips for Understanding +--- -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs +**Great job! You've completed this lesson!** diff --git a/lessons/dart/stage-2/level-6/lesson.md b/lessons/dart/stage-2/level-6/lesson.md index ad62233..411f715 100644 --- a/lessons/dart/stage-2/level-6/lesson.md +++ b/lessons/dart/stage-2/level-6/lesson.md @@ -20,24 +20,24 @@ You're progressing! Now you'll take more complex pseudocode and translate it int Here's some pseudocode: -```dart +``` [Pseudocode will be specific to the level] -```dart +``` **Your mission**: Translate this into Dart code in `main.dart.dart`. ### How to Run -```bash +``` cd ~/.local/share/learn/workspaces/dart/stage-2/level-6 -```dart +``` Then run your program. **Expected output:** -```dart +``` (Output will vary based on your implementation) -```dart +``` ### Success Checklist @@ -71,75 +71,22 @@ Check the `VIM_CHEATSHEET.md` for basic Vim commands! ## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -### Key Concepts - -- Review the code structure specific to Dart -- Understand the execution flow -- Learn common pitfalls and solutions - -### Next Steps - -Practice the code and experiment with variations! - ---- - -**Congratulations! Keep coding!** - - - -### Additional Content - -Understand the key concepts: - -- Review each function -- Understand the flow -- Learn the patterns used - - -### Code Review - -Key functions and their purpose: - -- Main function: Entry point -- Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```dart -void main() { - print("Hello, World!"); -} - -```dart - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: +``` +[Pseudocode will be specific to the level] +``` -1. **Structure**: The program follows standard dart conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions +### Explanation -### Testing Your Solution +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -Try these test cases to verify your code works correctly: +### Success Criteria -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does -### Tips for Understanding +--- -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs +**Great job! You've completed this lesson!** diff --git a/lessons/dart/stage-2/level-7/lesson.md b/lessons/dart/stage-2/level-7/lesson.md index 4955149..01dbeb5 100644 --- a/lessons/dart/stage-2/level-7/lesson.md +++ b/lessons/dart/stage-2/level-7/lesson.md @@ -20,24 +20,24 @@ You're progressing! Now you'll take more complex pseudocode and translate it int Here's some pseudocode: -```dart +``` [Pseudocode will be specific to the level] -```dart +``` **Your mission**: Translate this into Dart code in `main.dart.dart`. ### How to Run -```bash +``` cd ~/.local/share/learn/workspaces/dart/stage-2/level-7 -```dart +``` Then run your program. **Expected output:** -```dart +``` (Output will vary based on your implementation) -```dart +``` ### Success Checklist @@ -71,75 +71,22 @@ Check the `VIM_CHEATSHEET.md` for basic Vim commands! ## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -### Key Concepts - -- Review the code structure specific to Dart -- Understand the execution flow -- Learn common pitfalls and solutions - -### Next Steps - -Practice the code and experiment with variations! - ---- - -**Congratulations! Keep coding!** - - - -### Additional Content - -Understand the key concepts: - -- Review each function -- Understand the flow -- Learn the patterns used - - -### Code Review - -Key functions and their purpose: - -- Main function: Entry point -- Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```dart -void main() { - print("Hello, World!"); -} - -```dart - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: +``` +[Pseudocode will be specific to the level] +``` -1. **Structure**: The program follows standard dart conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions +### Explanation -### Testing Your Solution +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -Try these test cases to verify your code works correctly: +### Success Criteria -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does -### Tips for Understanding +--- -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs +**Great job! You've completed this lesson!** diff --git a/lessons/dart/stage-3/level-1/lesson.md b/lessons/dart/stage-3/level-1/lesson.md index f002531..243b56c 100644 --- a/lessons/dart/stage-3/level-1/lesson.md +++ b/lessons/dart/stage-3/level-1/lesson.md @@ -22,13 +22,13 @@ You're now ready for Stage 3! This is where you start thinking like a real progr Step 1: Write the pseudocode first -```dart +``` What should happen: 1. Print "Hello, [name]" Write your pseudocode in plain English below: (Your pseudocode here) -```dart +``` Step 2: Implement your pseudocode in Dart @@ -38,14 +38,14 @@ Create `main.dart.dart` with your solution. ### How to Run 1. **Run the code**: - ```bash + ``` dart hello.dart - ```dart + ``` **Expected output:** -```dart +``` Hello, World! -```dart +``` ### Success Checklist @@ -87,75 +87,26 @@ Check the `VIM_CHEATSHEET.md` for basic Vim commands! ## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -### Key Concepts - -- Review the code structure specific to Dart -- Understand the execution flow -- Learn common pitfalls and solutions - -### Next Steps - -Practice the code and experiment with variations! - ---- - -**Congratulations! Keep coding!** - - - -### Additional Content - -Understand the key concepts: - -- Review each function -- Understand the flow -- Learn the patterns used - - -### Code Review - -Key functions and their purpose: - -- Main function: Entry point -- Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```dart -void main() { - print("Hello, World!"); -} - -```dart - -### Code Breakdown +``` +What should happen: +1. Print "Hello, [name]" -This solution demonstrates the key concepts from this lesson: +Write your pseudocode in plain English below: +(Your pseudocode here) +``` -1. **Structure**: The program follows standard dart conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions +### Explanation -### Testing Your Solution +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -Try these test cases to verify your code works correctly: +### Success Criteria -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does -### Tips for Understanding +--- -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs +**Great job! You've completed this lesson!** diff --git a/lessons/dart/stage-3/level-2/lesson.md b/lessons/dart/stage-3/level-2/lesson.md index a3c8cae..af13a05 100644 --- a/lessons/dart/stage-3/level-2/lesson.md +++ b/lessons/dart/stage-3/level-2/lesson.md @@ -20,9 +20,9 @@ Another level, another challenge! You're getting stronger at analyzing problems. Read the problem carefully: -```dart +``` [Problem statement will be specific to this level] -```dart +``` **Step 1:** Write pseudocode in `pseudocode.txt` that solves this problem @@ -34,14 +34,14 @@ Create `main.dart.dart` with your solution. ### How to Run 1. **Run the code**: - ```bash + ``` dart hello.dart - ```dart + ``` **Expected output:** -```dart +``` Hello, World! -```dart +``` ### Success Checklist @@ -74,75 +74,22 @@ Check the `VIM_CHEATSHEET.md` for basic Vim commands! ## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -### Key Concepts - -- Review the code structure specific to Dart -- Understand the execution flow -- Learn common pitfalls and solutions - -### Next Steps - -Practice the code and experiment with variations! - ---- - -**Congratulations! Keep coding!** - - - -### Additional Content - -Understand the key concepts: - -- Review each function -- Understand the flow -- Learn the patterns used - - -### Code Review - -Key functions and their purpose: - -- Main function: Entry point -- Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```dart -void main() { - print("Hello, World!"); -} - -```dart - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: +``` +[Problem statement will be specific to this level] +``` -1. **Structure**: The program follows standard dart conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions +### Explanation -### Testing Your Solution +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -Try these test cases to verify your code works correctly: +### Success Criteria -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does -### Tips for Understanding +--- -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs +**Great job! You've completed this lesson!** diff --git a/lessons/dart/stage-3/level-3/lesson.md b/lessons/dart/stage-3/level-3/lesson.md index cf93dd5..c617b24 100644 --- a/lessons/dart/stage-3/level-3/lesson.md +++ b/lessons/dart/stage-3/level-3/lesson.md @@ -20,9 +20,9 @@ Another level, another challenge! You're getting stronger at analyzing problems. Read the problem carefully: -```dart +``` [Problem statement will be specific to this level] -```dart +``` **Step 1:** Write pseudocode in `pseudocode.txt` that solves this problem @@ -34,14 +34,14 @@ Create `main.dart.dart` with your solution. ### How to Run 1. **Run the code**: - ```bash + ``` dart hello.dart - ```dart + ``` **Expected output:** -```dart +``` Hello, World! -```dart +``` ### Success Checklist @@ -74,75 +74,22 @@ Check the `VIM_CHEATSHEET.md` for basic Vim commands! ## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -### Key Concepts - -- Review the code structure specific to Dart -- Understand the execution flow -- Learn common pitfalls and solutions - -### Next Steps - -Practice the code and experiment with variations! - ---- - -**Congratulations! Keep coding!** - - - -### Additional Content - -Understand the key concepts: - -- Review each function -- Understand the flow -- Learn the patterns used - - -### Code Review - -Key functions and their purpose: - -- Main function: Entry point -- Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```dart -void main() { - print("Hello, World!"); -} - -```dart - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: +``` +[Problem statement will be specific to this level] +``` -1. **Structure**: The program follows standard dart conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions +### Explanation -### Testing Your Solution +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -Try these test cases to verify your code works correctly: +### Success Criteria -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does -### Tips for Understanding +--- -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs +**Great job! You've completed this lesson!** diff --git a/lessons/dart/stage-3/level-4/lesson.md b/lessons/dart/stage-3/level-4/lesson.md index c9d4249..8b530e0 100644 --- a/lessons/dart/stage-3/level-4/lesson.md +++ b/lessons/dart/stage-3/level-4/lesson.md @@ -20,9 +20,9 @@ Another level, another challenge! You're getting stronger at analyzing problems. Read the problem carefully: -```dart +``` [Problem statement will be specific to this level] -```dart +``` **Step 1:** Write pseudocode in `pseudocode.txt` that solves this problem @@ -34,14 +34,14 @@ Create `main.dart.dart` with your solution. ### How to Run 1. **Run the code**: - ```bash + ``` dart hello.dart - ```dart + ``` **Expected output:** -```dart +``` Hello, World! -```dart +``` ### Success Checklist @@ -74,75 +74,22 @@ Check the `VIM_CHEATSHEET.md` for basic Vim commands! ## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -### Key Concepts - -- Review the code structure specific to Dart -- Understand the execution flow -- Learn common pitfalls and solutions - -### Next Steps - -Practice the code and experiment with variations! - ---- - -**Congratulations! Keep coding!** - - - -### Additional Content - -Understand the key concepts: - -- Review each function -- Understand the flow -- Learn the patterns used - - -### Code Review - -Key functions and their purpose: - -- Main function: Entry point -- Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```dart -void main() { - print("Hello, World!"); -} - -```dart - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: +``` +[Problem statement will be specific to this level] +``` -1. **Structure**: The program follows standard dart conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions +### Explanation -### Testing Your Solution +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -Try these test cases to verify your code works correctly: +### Success Criteria -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does -### Tips for Understanding +--- -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs +**Great job! You've completed this lesson!** diff --git a/lessons/dart/stage-3/level-5/lesson.md b/lessons/dart/stage-3/level-5/lesson.md index 85ff246..d65d8da 100644 --- a/lessons/dart/stage-3/level-5/lesson.md +++ b/lessons/dart/stage-3/level-5/lesson.md @@ -20,9 +20,9 @@ Another level, another challenge! You're getting stronger at analyzing problems. Read the problem carefully: -```dart +``` [Problem statement will be specific to this level] -```dart +``` **Step 1:** Write pseudocode in `pseudocode.txt` that solves this problem @@ -34,14 +34,14 @@ Create `main.dart.dart` with your solution. ### How to Run 1. **Run the code**: - ```bash + ``` dart hello.dart - ```dart + ``` **Expected output:** -```dart +``` Hello, World! -```dart +``` ### Success Checklist @@ -74,75 +74,22 @@ Check the `VIM_CHEATSHEET.md` for basic Vim commands! ## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -### Key Concepts - -- Review the code structure specific to Dart -- Understand the execution flow -- Learn common pitfalls and solutions - -### Next Steps - -Practice the code and experiment with variations! - ---- - -**Congratulations! Keep coding!** - - - -### Additional Content - -Understand the key concepts: - -- Review each function -- Understand the flow -- Learn the patterns used - - -### Code Review - -Key functions and their purpose: - -- Main function: Entry point -- Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```dart -void main() { - print("Hello, World!"); -} - -```dart - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: +``` +[Problem statement will be specific to this level] +``` -1. **Structure**: The program follows standard dart conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions +### Explanation -### Testing Your Solution +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -Try these test cases to verify your code works correctly: +### Success Criteria -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does -### Tips for Understanding +--- -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs +**Great job! You've completed this lesson!** diff --git a/lessons/dart/stage-3/level-6/lesson.md b/lessons/dart/stage-3/level-6/lesson.md index 4b62ed1..b90c301 100644 --- a/lessons/dart/stage-3/level-6/lesson.md +++ b/lessons/dart/stage-3/level-6/lesson.md @@ -20,9 +20,9 @@ Another level, another challenge! You're getting stronger at analyzing problems. Read the problem carefully: -```dart +``` [Problem statement will be specific to this level] -```dart +``` **Step 1:** Write pseudocode in `pseudocode.txt` that solves this problem @@ -34,14 +34,14 @@ Create `main.dart.dart` with your solution. ### How to Run 1. **Run the code**: - ```bash + ``` dart hello.dart - ```dart + ``` **Expected output:** -```dart +``` Hello, World! -```dart +``` ### Success Checklist @@ -74,75 +74,22 @@ Check the `VIM_CHEATSHEET.md` for basic Vim commands! ## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -### Key Concepts - -- Review the code structure specific to Dart -- Understand the execution flow -- Learn common pitfalls and solutions - -### Next Steps - -Practice the code and experiment with variations! - ---- - -**Congratulations! Keep coding!** - - - -### Additional Content - -Understand the key concepts: - -- Review each function -- Understand the flow -- Learn the patterns used - - -### Code Review - -Key functions and their purpose: - -- Main function: Entry point -- Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```dart -void main() { - print("Hello, World!"); -} - -```dart - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: +``` +[Problem statement will be specific to this level] +``` -1. **Structure**: The program follows standard dart conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions +### Explanation -### Testing Your Solution +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -Try these test cases to verify your code works correctly: +### Success Criteria -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does -### Tips for Understanding +--- -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs +**Great job! You've completed this lesson!** diff --git a/lessons/dart/stage-3/level-7/lesson.md b/lessons/dart/stage-3/level-7/lesson.md index 23e86b1..24f34f6 100644 --- a/lessons/dart/stage-3/level-7/lesson.md +++ b/lessons/dart/stage-3/level-7/lesson.md @@ -20,9 +20,9 @@ Another level, another challenge! You're getting stronger at analyzing problems. Read the problem carefully: -```dart +``` [Problem statement will be specific to this level] -```dart +``` **Step 1:** Write pseudocode in `pseudocode.txt` that solves this problem @@ -34,14 +34,14 @@ Create `main.dart.dart` with your solution. ### How to Run 1. **Run the code**: - ```bash + ``` dart hello.dart - ```dart + ``` **Expected output:** -```dart +``` Hello, World! -```dart +``` ### Success Checklist @@ -74,75 +74,22 @@ Check the `VIM_CHEATSHEET.md` for basic Vim commands! ## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -### Key Concepts - -- Review the code structure specific to Dart -- Understand the execution flow -- Learn common pitfalls and solutions - -### Next Steps - -Practice the code and experiment with variations! - ---- - -**Congratulations! Keep coding!** - - - -### Additional Content - -Understand the key concepts: - -- Review each function -- Understand the flow -- Learn the patterns used - - -### Code Review - -Key functions and their purpose: - -- Main function: Entry point -- Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```dart -void main() { - print("Hello, World!"); -} - -```dart - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: +``` +[Problem statement will be specific to this level] +``` -1. **Structure**: The program follows standard dart conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions +### Explanation -### Testing Your Solution +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -Try these test cases to verify your code works correctly: +### Success Criteria -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does -### Tips for Understanding +--- -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs +**Great job! You've completed this lesson!** diff --git a/lessons/dart/stage-4/level-1/lesson.md b/lessons/dart/stage-4/level-1/lesson.md index 0f4b349..38c7c2d 100644 --- a/lessons/dart/stage-4/level-1/lesson.md +++ b/lessons/dart/stage-4/level-1/lesson.md @@ -30,14 +30,14 @@ Requirements: ### How to Run 1. **Run the code**: - ```bash + ``` dart hello.dart - ```dart + ``` **Expected output:** -```dart +``` Hello, World! -```dart +``` ### How to Approach This @@ -113,42 +113,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```dart -void main() { - print("Hello, World!"); -} - -```dart - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard dart conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/dart/stage-4/level-2/lesson.md b/lessons/dart/stage-4/level-2/lesson.md index 355648b..3bc9da3 100644 --- a/lessons/dart/stage-4/level-2/lesson.md +++ b/lessons/dart/stage-4/level-2/lesson.md @@ -26,14 +26,14 @@ Design and implement a complete Dart solution in `main.dart.dart`. ### How to Run 1. **Run the code**: - ```bash + ``` dart hello.dart - ```dart + ``` **Expected output:** -```dart +``` Hello, World! -```dart +``` ### Your Approach @@ -106,42 +106,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```dart -void main() { - print("Hello, World!"); -} - -```dart - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard dart conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/dart/stage-4/level-3/lesson.md b/lessons/dart/stage-4/level-3/lesson.md index 9cda42c..14bf980 100644 --- a/lessons/dart/stage-4/level-3/lesson.md +++ b/lessons/dart/stage-4/level-3/lesson.md @@ -26,14 +26,14 @@ Design and implement a complete Dart solution in `main.dart.dart`. ### How to Run 1. **Run the code**: - ```bash + ``` dart hello.dart - ```dart + ``` **Expected output:** -```dart +``` Hello, World! -```dart +``` ### Your Approach @@ -106,42 +106,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```dart -void main() { - print("Hello, World!"); -} - -```dart - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard dart conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/dart/stage-4/level-4/lesson.md b/lessons/dart/stage-4/level-4/lesson.md index 55144ca..74e99ac 100644 --- a/lessons/dart/stage-4/level-4/lesson.md +++ b/lessons/dart/stage-4/level-4/lesson.md @@ -26,14 +26,14 @@ Design and implement a complete Dart solution in `main.dart.dart`. ### How to Run 1. **Run the code**: - ```bash + ``` dart hello.dart - ```dart + ``` **Expected output:** -```dart +``` Hello, World! -```dart +``` ### Your Approach @@ -106,42 +106,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```dart -void main() { - print("Hello, World!"); -} - -```dart - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard dart conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/dart/stage-4/level-5/lesson.md b/lessons/dart/stage-4/level-5/lesson.md index 98c3f78..79fbf44 100644 --- a/lessons/dart/stage-4/level-5/lesson.md +++ b/lessons/dart/stage-4/level-5/lesson.md @@ -26,14 +26,14 @@ Design and implement a complete Dart solution in `main.dart.dart`. ### How to Run 1. **Run the code**: - ```bash + ``` dart hello.dart - ```dart + ``` **Expected output:** -```dart +``` Hello, World! -```dart +``` ### Your Approach @@ -106,42 +106,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```dart -void main() { - print("Hello, World!"); -} - -```dart - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard dart conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/dart/stage-4/level-6/lesson.md b/lessons/dart/stage-4/level-6/lesson.md index cb8e911..fdc5156 100644 --- a/lessons/dart/stage-4/level-6/lesson.md +++ b/lessons/dart/stage-4/level-6/lesson.md @@ -26,14 +26,14 @@ Design and implement a complete Dart solution in `main.dart.dart`. ### How to Run 1. **Run the code**: - ```bash + ``` dart hello.dart - ```dart + ``` **Expected output:** -```dart +``` Hello, World! -```dart +``` ### Your Approach @@ -106,42 +106,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```dart -void main() { - print("Hello, World!"); -} - -```dart - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard dart conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/dart/stage-4/level-7/lesson.md b/lessons/dart/stage-4/level-7/lesson.md index dd64b8f..bb2e3f6 100644 --- a/lessons/dart/stage-4/level-7/lesson.md +++ b/lessons/dart/stage-4/level-7/lesson.md @@ -26,14 +26,14 @@ Design and implement a complete Dart solution in `main.dart.dart`. ### How to Run 1. **Run the code**: - ```bash + ``` dart hello.dart - ```dart + ``` **Expected output:** -```dart +``` Hello, World! -```dart +``` ### Your Approach @@ -106,42 +106,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```dart -void main() { - print("Hello, World!"); -} - -```dart - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard dart conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/dart/stage-5/level-1/lesson.md b/lessons/dart/stage-5/level-1/lesson.md index 268ee6c..718e842 100644 --- a/lessons/dart/stage-5/level-1/lesson.md +++ b/lessons/dart/stage-5/level-1/lesson.md @@ -30,14 +30,14 @@ You're going to build a complete Dart application. This is a real project that c ### How to Run 1. **Run the code**: - ```bash + ``` dart hello.dart - ```dart + ``` **Expected output:** -```dart +``` Hello, World! -```dart +``` ### Project Requirements @@ -154,42 +154,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```dart -void main() { - print("Hello, World!"); -} - -```dart - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard dart conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/dart/stage-5/level-2/lesson.md b/lessons/dart/stage-5/level-2/lesson.md index 4228d92..ed03e85 100644 --- a/lessons/dart/stage-5/level-2/lesson.md +++ b/lessons/dart/stage-5/level-2/lesson.md @@ -34,14 +34,14 @@ Design and implement a Dart project that demonstrates your mastery of the langua ### How to Run 1. **Run the code**: - ```bash + ``` dart hello.dart - ```dart + ``` **Expected output:** -```dart +``` Hello, World! -```dart +``` ### Project Suggestions @@ -129,42 +129,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```dart -void main() { - print("Hello, World!"); -} - -```dart - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard dart conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/dart/stage-5/level-3/lesson.md b/lessons/dart/stage-5/level-3/lesson.md index 137294a..6f20477 100644 --- a/lessons/dart/stage-5/level-3/lesson.md +++ b/lessons/dart/stage-5/level-3/lesson.md @@ -34,14 +34,14 @@ Design and implement a Dart project that demonstrates your mastery of the langua ### How to Run 1. **Run the code**: - ```bash + ``` dart hello.dart - ```dart + ``` **Expected output:** -```dart +``` Hello, World! -```dart +``` ### Project Suggestions @@ -129,42 +129,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```dart -void main() { - print("Hello, World!"); -} - -```dart - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard dart conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/dart/stage-5/level-4/lesson.md b/lessons/dart/stage-5/level-4/lesson.md index 592aa4b..e0b1f1a 100644 --- a/lessons/dart/stage-5/level-4/lesson.md +++ b/lessons/dart/stage-5/level-4/lesson.md @@ -34,14 +34,14 @@ Design and implement a Dart project that demonstrates your mastery of the langua ### How to Run 1. **Run the code**: - ```bash + ``` dart hello.dart - ```dart + ``` **Expected output:** -```dart +``` Hello, World! -```dart +``` ### Project Suggestions @@ -129,42 +129,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```dart -void main() { - print("Hello, World!"); -} - -```dart - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard dart conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/dart/stage-5/level-5/lesson.md b/lessons/dart/stage-5/level-5/lesson.md index d974d51..ffa22ba 100644 --- a/lessons/dart/stage-5/level-5/lesson.md +++ b/lessons/dart/stage-5/level-5/lesson.md @@ -34,14 +34,14 @@ Design and implement a Dart project that demonstrates your mastery of the langua ### How to Run 1. **Run the code**: - ```bash + ``` dart hello.dart - ```dart + ``` **Expected output:** -```dart +``` Hello, World! -```dart +``` ### Project Suggestions @@ -129,42 +129,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```dart -void main() { - print("Hello, World!"); -} - -```dart - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard dart conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/dart/stage-5/level-6/lesson.md b/lessons/dart/stage-5/level-6/lesson.md index 28f4db0..6a388d5 100644 --- a/lessons/dart/stage-5/level-6/lesson.md +++ b/lessons/dart/stage-5/level-6/lesson.md @@ -34,14 +34,14 @@ Design and implement a Dart project that demonstrates your mastery of the langua ### How to Run 1. **Run the code**: - ```bash + ``` dart hello.dart - ```dart + ``` **Expected output:** -```dart +``` Hello, World! -```dart +``` ### Project Suggestions @@ -129,42 +129,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```dart -void main() { - print("Hello, World!"); -} - -```dart - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard dart conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/dart/stage-5/level-7/lesson.md b/lessons/dart/stage-5/level-7/lesson.md index 06bc14c..84e0881 100644 --- a/lessons/dart/stage-5/level-7/lesson.md +++ b/lessons/dart/stage-5/level-7/lesson.md @@ -34,14 +34,14 @@ Design and implement a Dart project that demonstrates your mastery of the langua ### How to Run 1. **Run the code**: - ```bash + ``` dart hello.dart - ```dart + ``` **Expected output:** -```dart +``` Hello, World! -```dart +``` ### Project Suggestions @@ -129,42 +129,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```dart -void main() { - print("Hello, World!"); -} - -```dart - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard dart conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/go/stage-1/level-1/lesson.md b/lessons/go/stage-1/level-1/lesson.md index 0d25b22..6ee18ab 100644 --- a/lessons/go/stage-1/level-1/lesson.md +++ b/lessons/go/stage-1/level-1/lesson.md @@ -25,7 +25,7 @@ Welcome to your first step into Go programming! Today, you'll learn how to creat **Copy the following code EXACTLY as shown below into a new file called `hello.go`** -```go +``` package main import "fmt" @@ -33,7 +33,7 @@ import "fmt" func main() { fmt.Println("Hello, World!") } -```go +``` --- @@ -41,22 +41,22 @@ func main() { 1. **Open your terminal** (or command prompt) 2. **Navigate to where you saved your file**: - ```bash + ``` cd /path/to/your/folder - ```go + ``` 3. **Create a Go module** (if this is your first program in the directory): - ```bash + ``` go mod init hello - ```go + ``` 4. **Run your program**: - ```bash + ``` go run hello.go - ```go + ``` **Expected output:** -```go +``` Hello, World! -```go +``` --- @@ -108,25 +108,25 @@ Remember to check the `VIM_CHEATSHEET.md` in the root directory for basic Vim co ### Code Breakdown -```go +``` package main -```go +``` - **`package`** = Keyword that defines a package - **`main`** = Special package name that indicates an executable program - Every Go program must belong to a package -```go +``` import "fmt" -```go +``` - **`import`** = Keyword to include other packages - **`"fmt"`** = Format package that provides functions for formatted I/O - **Needed for** `fmt.Println()` function -```go +``` func main() { fmt.Println("Hello, World!") } -```go +``` - **`func`** = Keyword to define a function - **`main`** = Special function name that's the entry point of every Go program - **`()`** = Parameters list (empty means no inputs needed) @@ -142,10 +142,10 @@ func main() { ### Go Modules Go modules manage dependencies and versions: -```bash +``` go mod init hello # Creates go.mod file go mod tidy # Downloads required dependencies -```go +``` ### Common Errors & Solutions @@ -166,7 +166,7 @@ go mod tidy # Downloads required dependencies --- - **Congratulations! You've written your first Go program!** + **Congratulations! You've written your first Go program!** *Keep moving forward - next up: Variables!* @@ -193,46 +193,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```go -package main - -import "fmt" - -func main() { - fmt.Println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard go conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/go/stage-1/level-2/lesson.md b/lessons/go/stage-1/level-2/lesson.md index 32555fb..649af47 100644 --- a/lessons/go/stage-1/level-2/lesson.md +++ b/lessons/go/stage-1/level-2/lesson.md @@ -25,7 +25,7 @@ Welcome to the world of variables! Today you'll learn how to store and use data **Copy the following code into a new file called `variables.go`** -```go +``` package main import "fmt" @@ -35,25 +35,25 @@ func main() { var name string = "Alex" var city string = "New York" var hobby string = "programming" - + // You can also use short declaration (available inside functions only) country := "USA" - + // Number variables (integers) var age int = 25 var height int = 175 var score int = 100 - + // Number variables (floating point) var temperature float64 = 98.6 var price float64 = 29.99 var weight float64 = 150.5 - + // Boolean variables (true/false) var isStudent bool = true var isEmployed bool = false var isHappy bool = true - + // Print all the variables fmt.Println("=== Personal Info ===") fmt.Println("Name: " + name) @@ -61,59 +61,59 @@ func main() { fmt.Println("Hobby: " + hobby) fmt.Println("Country: " + country) fmt.Println() - + fmt.Println("=== Measurements ===") fmt.Println("Age:", age, "years old") fmt.Println("Height:", height, "cm") fmt.Println("Score:", score, "points") fmt.Println() - + fmt.Println("=== Decimal Measurements ===") fmt.Println("Temperature:", temperature, "degrees") fmt.Println("Price: $", price) fmt.Println("Weight:", weight, "lbs") fmt.Println() - + fmt.Println("=== Status ===") fmt.Println("Student:", isStudent) fmt.Println("Employed:", isEmployed) fmt.Println("Happy:", isHappy) - + // Multiple variable declarations var ( firstName string = "John" lastName string = "Doe" age2 int = 35 ) - + fmt.Println() fmt.Println("=== Multiple Declaration Example ===") fmt.Println("Full Name:", firstName, lastName) fmt.Println("Age:", age2) - + // Go's static typing prevents type mismatches // The following would cause an error: // var number int = "this won't work" // Type mismatch error } -```go +``` --- ### How to Execute 1. **Create or navigate to a Go module directory** (if not already in one): - ```bash + ``` mkdir variables-example && cd variables-example go mod init variables - ```go + ``` 2. **Copy the code into `variables.go`** 3. **Run your program**: - ```bash + ``` go run variables.go - ```bash + ``` **Expected output:** -```go +``` === Personal Info === Name: Alex City: New York @@ -138,7 +138,7 @@ Happy: true === Multiple Declaration Example === Full Name: John Doe Age: 35 -```go +``` --- @@ -194,25 +194,25 @@ Go has several important concepts about variables: ### Code Breakdown -```go +``` var name string = "Alex" -```go +``` - **`var`** = Keyword to declare a variable - **`name`** = Variable name (follows Go naming conventions) - **`string`** = Type declaration (Go is statically typed) - **`=`** = Assignment operator (stores value on right into variable on left) - **`"Alex"`** = String value (text in quotes) -```go +``` country := "USA" -```go +``` - **`:=`** = Short variable declaration (declare and initialize) - **Available only** inside functions in Go - **Type inferred** by Go from the assigned value -```go +``` fmt.Println("Name: " + name) -```go +``` - **`+`** = String concatenation operator (joins strings together) - The variable `name` gets its value inserted into the output string @@ -221,22 +221,22 @@ fmt.Println("Name: " + name) Go has three main ways to declare variables: 1. **Standard declaration**: -```go +``` var name string = "Alex" var age int = 25 -```go +``` 2. **Type omitted (inferred)**: -```go +``` var name = "Alex" // Type inferred as string var age = 25 // Type inferred as int -```go +``` 3. **Short declaration** (inside functions only): -```go +``` name := "Alex" // Type inferred as string age := 25 // Type inferred as int -```go +``` ### Variable Naming Rules @@ -272,39 +272,39 @@ age := 25 // Type inferred as int In Go, every variable has a zero value when declared without initialization: -```go +``` var name string // Zero value: "" var age int // Zero value: 0 var height float64 // Zero value: 0.0 var isTrue bool // Zero value: false -```go +``` ### Multiple Variable Declarations **Group syntax**: -```go +``` var ( name string = "Alex" age int = 25 city string = "New York" ) -```go +``` **Same type on one line**: -```go +``` var name, city string = "Alex", "New York" var age1, age2 int = 25, 30 -```go +``` ### Static Typing Go's static typing means you must be explicit about types, and type mismatches cause compile errors: -```go +``` var age int = 25 // This will cause a compile error: // age = "twenty five" // Cannot assign string to int variable -```go +``` ### Common Errors & Solutions @@ -326,7 +326,7 @@ var age int = 25 Try this modified version: -```go +``` package main import "fmt" @@ -336,39 +336,39 @@ func main() { var currentYear int = 2025 var birthYear int = 2000 var calculatedAge int = currentYear - birthYear - + fmt.Println("Born in", birthYear, ", now it's", currentYear) fmt.Println("Calculated age:", calculatedAge, "years old") - + // Working with different number types var integerNum int = 10 var floatNum float64 = 3.5 var result float64 = float64(integerNum) + floatNum // Type conversion needed - + fmt.Println("Integer:", integerNum) fmt.Println("Float:", floatNum) fmt.Println("Result:", result) - + // Working with strings and characters var firstName string = "Jane" var lastName string = "Smith" var fullName string = firstName + " " + lastName - + fmt.Println("Full name:", fullName) - + // Using different boolean operations var isStudent bool = true var isEmployed bool = false var isRetired bool = false - + fmt.Println("Is student AND not employed:", isStudent && !isEmployed) fmt.Println("Is employed OR retired:", isEmployed || isRetired) } -```go +``` --- - **Excellent work! You now understand variables - the foundation of all programming!** + **Excellent work! You now understand variables - the foundation of all programming!** *Ready for the next challenge? Let's do some math with our variables!* @@ -395,46 +395,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```go -package main - -import "fmt" - -func main() { - fmt.Println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard go conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/go/stage-1/level-3/lesson.md b/lessons/go/stage-1/level-3/lesson.md index 366a52a..25d2e99 100644 --- a/lessons/go/stage-1/level-3/lesson.md +++ b/lessons/go/stage-1/level-3/lesson.md @@ -25,7 +25,7 @@ Time to do some math! Today you'll learn how to perform mathematical operations **Copy the following code into a new file called `math.go`** -```go +``` package main import "fmt" @@ -33,133 +33,133 @@ import "fmt" func main() { // Basic arithmetic operations fmt.Println("=== Basic Arithmetic ===") - + // Addition sum := 5 + 3 fmt.Println("5 + 3 =", sum) - + // Subtraction difference := 10 - 4 fmt.Println("10 - 4 =", difference) - + // Multiplication product := 6 * 7 fmt.Println("6 * 7 =", product) - + // Division (integer division when both operands are integers) quotient := 15 / 3 fmt.Println("15 / 3 =", quotient) - + // Modulo (remainder) remainder := 17 % 5 fmt.Println("17 % 5 =", remainder, "(remainder)") - + fmt.Println() fmt.Println("=== Integer vs Float Division ===") - + // Integer division intResult := 7 / 2 fmt.Println("Integer division 7/2 =", intResult) // Output: 3 (truncated) - + // Float division floatResult := 7.0 / 2.0 fmt.Println("Float division 7.0/2.0 =", floatResult) // Output: 3.5 - + // Mixed division (int converted to float) mixedResult := float64(7) / 2.0 fmt.Println("Mixed division float64(7)/2.0 =", mixedResult) - + fmt.Println() fmt.Println("=== Order of Operations ===") - + // Parentheses change the order withParentheses := (10 + 5) * 2 fmt.Println("(10 + 5) * 2 =", withParentheses) - + withoutParentheses := 10 + 5 * 2 fmt.Println("10 + 5 * 2 =", withoutParentheses) - + fmt.Println() fmt.Println("=== Real-World Calculations ===") - + // Calculate area of rectangle length := 10 width := 5 area := length * width fmt.Println("Rectangle area (", length, "x", width, "):", area) - + // Calculate circle area (π * r²) radius := 7.0 circleArea := 3.14159 * radius * radius fmt.Println("Circle area (radius", radius, "):", circleArea) - + // Calculate average of three numbers num1 := 10 num2 := 20 num3 := 30 average := (num1 + num2 + num3) / 3 fmt.Println("Average of", num1, ",", num2, ",", num3, ":", average) - + fmt.Println() fmt.Println("=== Increment and Decrement ===") - + // Go has increment (++) and decrement (--) operators, but they are statements, not expressions count := 5 fmt.Println("Initial count:", count) - + count++ // Increment by 1 (equivalent to: count = count + 1) fmt.Println("After increment:", count) - + count-- // Decrement by 1 (equivalent to: count = count - 1) fmt.Println("After decrement:", count) - + fmt.Println() fmt.Println("=== Compound Assignment Operations ===") - + value := 10 fmt.Println("Initial value:", value) - + value += 5 // Same as: value = value + 5 fmt.Println("After += 5:", value) - + value -= 3 // Same as: value = value - 3 fmt.Println("After -= 3:", value) - + value *= 2 // Same as: value = value * 2 fmt.Println("After *= 2:", value) - + value /= 4 // Same as: value = value / 4 fmt.Println("After /= 4:", value) value %= 3 // Same as: value = value % 3 fmt.Println("After %= 3:", value) - + fmt.Println() fmt.Println("=== Advanced Math Operations ===") - + // Go doesn't have a built-in exponentiation operator // We need to use the math package for exponentiation importMathExample() - + // Integer overflow example (with smaller integer types) var smallInt int8 = 127 // Maximum value for int8 fmt.Println("Max int8 value:", smallInt) - + // This would cause overflow (but Go will catch it at runtime in some cases) // For now, just showing the concept: overflown := int8(smallInt) + 1 fmt.Println("Max int8 + 1 (overflow):", overflown) // Will wrap around to -128 - + fmt.Println() fmt.Println("=== Type Conversion in Math ===") - + // When doing math with different types, you need to convert var intNum int = 10 var floatNum float64 = 3.5 - + // Need to convert to the same type result1 := float64(intNum) + floatNum result2 := intNum + int(floatNum) // This truncates floatNum to 3 - + fmt.Println("intNum + floatNum (with conversion):", result1) fmt.Println("intNum + int(floatNum) (truncated):", result2) } @@ -169,12 +169,12 @@ func importMathExample() { import ( // We can't import inside functions in Go, so this is just illustrative "math" ) - + // Since we can't actually import in a function, let's show how it would work: // squareRoot := math.Sqrt(16) // Square root // power := math.Pow(2, 3) // 2 to the power of 3 // rounded := math.Round(4.7) // Round to nearest integer - + // For this example, we'll just show integer exponentiation base := 2 power := 3 @@ -184,11 +184,11 @@ func importMathExample() { } fmt.Println("2^3 (manual):", result) } -```go +``` Actually, let me fix the above code as we can't import inside functions in Go. Here's the corrected version: -```go +``` package main import ( @@ -199,177 +199,177 @@ import ( func main() { // Basic arithmetic operations fmt.Println("=== Basic Arithmetic ===") - + // Addition sum := 5 + 3 fmt.Println("5 + 3 =", sum) - + // Subtraction difference := 10 - 4 fmt.Println("10 - 4 =", difference) - + // Multiplication product := 6 * 7 fmt.Println("6 * 7 =", product) - + // Division (integer division when both operands are integers) quotient := 15 / 3 fmt.Println("15 / 3 =", quotient) - + // Modulo (remainder) remainder := 17 % 5 fmt.Println("17 % 5 =", remainder, "(remainder)") - + fmt.Println() fmt.Println("=== Integer vs Float Division ===") - + // Integer division intResult := 7 / 2 fmt.Println("Integer division 7/2 =", intResult) // Output: 3 (truncated) - + // Float division floatResult := 7.0 / 2.0 fmt.Println("Float division 7.0/2.0 =", floatResult) // Output: 3.5 - + // Mixed division (int converted to float) mixedResult := float64(7) / 2.0 fmt.Println("Mixed division float64(7)/2.0 =", mixedResult) - + fmt.Println() fmt.Println("=== Order of Operations ===") - + // Parentheses change the order withParentheses := (10 + 5) * 2 fmt.Println("(10 + 5) * 2 =", withParentheses) - + withoutParentheses := 10 + 5 * 2 fmt.Println("10 + 5 * 2 =", withoutParentheses) - + fmt.Println() fmt.Println("=== Real-World Calculations ===") - + // Calculate area of rectangle length := 10 width := 5 area := length * width fmt.Println("Rectangle area (", length, "x", width, "):", area) - + // Calculate circle area (π * r²) radius := 7.0 circleArea := 3.14159 * radius * radius fmt.Println("Circle area (radius", radius, "):", circleArea) - + // Calculate average of three numbers num1 := 10 num2 := 20 num3 := 30 average := (num1 + num2 + num3) / 3 fmt.Println("Average of", num1, ",", num2, ",", num3, ":", average) - + fmt.Println() fmt.Println("=== Increment and Decrement ===") - + // Go has increment (++) and decrement (--) operators, but they are statements, not expressions count := 5 fmt.Println("Initial count:", count) - + count++ // Increment by 1 (equivalent to: count = count + 1) fmt.Println("After increment:", count) - + count-- // Decrement by 1 (equivalent to: count = count - 1) fmt.Println("After decrement:", count) - + fmt.Println() fmt.Println("=== Compound Assignment Operations ===") - + value := 10 fmt.Println("Initial value:", value) - + value += 5 // Same as: value = value + 5 fmt.Println("After += 5:", value) - + value -= 3 // Same as: value = value - 3 fmt.Println("After -= 3:", value) - + value *= 2 // Same as: value = value * 2 fmt.Println("After *= 2:", value) - + value /= 4 // Same as: value = value / 4 fmt.Println("After /= 4:", value) value %= 3 // Same as: value = value % 3 fmt.Println("After %= 3:", value) - + fmt.Println() fmt.Println("=== Advanced Math with Math Package ===") - + // Square root sqrtResult := math.Sqrt(16) fmt.Println("Square root of 16:", sqrtResult) - + // Power powerResult := math.Pow(2, 3) fmt.Println("2^3:", powerResult) - + // Round rounded := math.Round(4.7) fmt.Println("Round 4.7:", rounded) - + // Ceiling ceiling := math.Ceil(4.2) fmt.Println("Ceiling of 4.2:", ceiling) - + // Floor floor := math.Floor(4.7) fmt.Println("Floor of 4.7:", floor) - + // Absolute value absValue := math.Abs(-10.5) fmt.Println("Absolute value of -10.5:", absValue) - + fmt.Println() fmt.Println("=== Integer Overflow Example ===") - + // Integer overflow example (with smaller integer types) var smallInt int8 = 127 // Maximum value for int8 fmt.Println("Max int8 value:", smallInt) - + // This demonstrates overflow behavior overflown := int8(smallInt) + 1 fmt.Println("Max int8 + 1 (overflow):", overflown) // Will wrap around to -128 - + fmt.Println() fmt.Println("=== Type Conversion in Math ===") - + // When doing math with different types, you need to convert var intNum int = 10 var floatNum float64 = 3.5 - + // Need to convert to the same type result1 := float64(intNum) + floatNum result2 := intNum + int(floatNum) // This truncates floatNum to 3 - + fmt.Println("intNum + floatNum (with conversion):", result1) fmt.Println("intNum + int(floatNum) (truncated):", result2) } -```go +``` --- ### How to Execute 1. **Create or navigate to a Go module directory** (if not already in one): - ```bash + ``` mkdir math-example && cd math-example go mod init math - ```go + ``` 2. **Copy the code into `math.go`** 3. **Run your program**: - ```bash + ``` go run math.go - ```bash + ``` **Expected output:** -```go +``` === Basic Arithmetic === 5 + 3 = 8 10 - 4 = 6 @@ -419,7 +419,7 @@ Max int8 + 1 (overflow): -128 === Type Conversion in Math === intNum + floatNum (with conversion): 13.5 intNum + int(floatNum) (truncated): 13 -```go +``` --- @@ -475,18 +475,18 @@ In Go math, you saw some operators: ### Code Breakdown -```go +``` sum := 5 + 3 fmt.Println("5 + 3 =", sum) -```go +``` - **`:=`** = Short variable declaration (declare and initialize) - **`+`** = Addition operator (performs arithmetic addition) - **Variable declaration** happens at the same time as initialization -```go +``` remainder := 17 % 5 fmt.Println("17 % 5 =", remainder, "(remainder)") -```go +``` - **`%`** = Modulo operator (returns the remainder after division) - 17 ÷ 5 = 3 remainder 2, so 17 % 5 = 2 - Useful for checking if numbers are even (n % 2 == 0) or cycling through values @@ -495,11 +495,11 @@ fmt.Println("17 % 5 =", remainder, "(remainder)") In Go, when both operands in division are integers, the result is truncated to an integer: -```go +``` result := 7 / 2 // Result is 3 (integer truncated) result := 7.0 / 2.0 // Result is 3.5 (float division) result := 7 / 2.0 // Result is 3.5 (mixed, converted to float) -```go +``` ### Order of Operations (PEMDAS) @@ -510,19 +510,19 @@ Go follows the standard mathematical order of operations: 3. **A**ddition `+`, **S**ubtraction `-` (left to right) Examples: -```go +``` // Without parentheses: Multiplication before addition result := 10 + 5 * 2 // = 10 + 10 = 20 (not 30!) // With parentheses: Addition before multiplication result := (10 + 5) * 2 // = 15 * 2 = 30 -```go +``` ### Go's Math Package The math package provides advanced mathematical functions: -```go +``` import "math" // Basic operations @@ -542,52 +542,52 @@ math.Pow(2, 3) // 2 to the power of 3: 8.0 // Constants math.Pi // π: 3.141592653589793 math.E // e: 2.718281828459045 -```go +``` ### Increment and Decrement Operators Go has `++` and `--` operators, but they are statements, not expressions: -```go +``` count := 5 count++ // OK: increments count by 1 count-- // OK: decrements count by 1 // NOT OK in Go (unlike C/C++/Java): // result := count++ // Syntax error! Can't use as expression -```go +``` ### Compound Assignment Operators Go supports all compound assignment operators: -```go +``` value := 10 value += 5 // Same as: value = value + 5 value -= 3 // Same as: value = value - 3 value *= 2 // Same as: value = value * 2 value /= 4 // Same as: value = value / 4 value %= 3 // Same as: value = value % 3 -```go +``` ### Important Go Math Notes **No exponentiation operator**: Go doesn't have a `^` operator for exponentiation (it's used for bitwise XOR). Use `math.Pow()` instead: -```go +``` result := math.Pow(2, 3) // 2^3 = 8 -```go +``` **Integer overflow**: Go has types of different sizes. When you exceed the limit of a type, it wraps around: -```go +``` var small int8 = 127 // Maximum for int8 small = small + 1 // Now small becomes -128 (overflow) -```go +``` **Type conversions**: In Go, you must explicitly convert between numeric types: -```go +``` var intVal int = 5 var floatVal float64 = 2.5 @@ -597,7 +597,7 @@ var floatVal float64 = 2.5 // Must convert explicitly: result1 := float64(intVal) + floatVal // Convert int to float64 result2 := intVal + int(floatVal) // Convert float64 to int (truncates) -```go +``` ### Common Errors & Solutions @@ -612,7 +612,7 @@ result2 := intVal + int(floatVal) // Convert float64 to int (truncates) Try this complex calculation: -```go +``` package main import ( @@ -622,41 +622,41 @@ import ( func main() { fmt.Println("=== Complex Math Example ===") - + // Compound interest calculation principal := 1000.0 // Initial amount rate := 0.05 // 5% annual interest rate timesCompounded := 12.0 // Compounded monthly years := 10.0 // 10 years - + // Formula: A = P(1 + r/n)^(nt) amount := principal * math.Pow(1 + rate/timesCompounded, timesCompounded * years) - + fmt.Println("Initial investment: $", principal) fmt.Printf("After %.0f years at %.0f%% interest: $%.2f\n", years, rate*100, amount) - + // Calculate percentage change original := 100.0 newAmount := 125.0 percentageChange := ((newAmount - original) / original) * 100 fmt.Printf("Percentage change from %.0f to %.0f: %.2f%%\n", original, newAmount, percentageChange) - + // Pythagorean theorem (a² + b² = c²) sideA := 3.0 sideB := 4.0 hypotenuse := math.Sqrt(sideA*sideA + sideB*sideB) fmt.Printf("Right triangle with sides %.0f and %.0f has hypotenuse: %.2f\n", sideA, sideB, hypotenuse) - + // Working with different number sizes and overflow var counter int32 = 2147483647 // Maximum for int32 fmt.Println("Max int32:", counter) fmt.Println("Max int32 + 1:", counter + 1) // This will overflow to negative } -```go +``` --- - **Excellent work! You're becoming a mathematical wizard in Go!** + **Excellent work! You're becoming a mathematical wizard in Go!** *Ready for the next challenge? Let's learn how to get input from users!* @@ -683,46 +683,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```go -package main - -import "fmt" - -func main() { - fmt.Println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard go conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/go/stage-1/level-4/lesson.md b/lessons/go/stage-1/level-4/lesson.md index c5991ed..f950f0b 100644 --- a/lessons/go/stage-1/level-4/lesson.md +++ b/lessons/go/stage-1/level-4/lesson.md @@ -25,7 +25,7 @@ Now let's make our programs interactive! Today you'll learn how to get input fro **Copy the following code into a new file called `input.go`** -```go +``` package main import ( @@ -38,14 +38,14 @@ import ( func main() { reader := bufio.NewReader(os.Stdin) - + fmt.Println("=== Interactive Greeting Program ===") // Get input from user fmt.Print("What's your name? ") name, _ := reader.ReadString('\n') name = strings.TrimSpace(name) // Remove newline character fmt.Println("Hello,", name, "! Nice to meet you!") - + fmt.Println() fmt.Println("=== Simple Calculator ===") // Get two numbers from user @@ -57,7 +57,7 @@ func main() { fmt.Println("Invalid number entered!") return } - + fmt.Print("Enter second number: ") input2, _ := reader.ReadString('\n') input2 = strings.TrimSpace(input2) @@ -66,19 +66,19 @@ func main() { fmt.Println("Invalid number entered!") return } - + // Perform calculations sum := num1 + num2 difference := num1 - num2 product := num1 * num2 quotient := num1 / num2 - + // Display results fmt.Printf("%.2f + %.2f = %.2f\n", num1, num2, sum) fmt.Printf("%.2f - %.2f = %.2f\n", num1, num2, difference) fmt.Printf("%.2f * %.2f = %.2f\n", num1, num2, product) fmt.Printf("%.2f / %.2f = %.2f\n", num1, num2, quotient) - + fmt.Println() fmt.Println("=== Age Calculator ===") // Ask for birth year and calculate age @@ -90,45 +90,45 @@ func main() { fmt.Println("Please enter a valid year!") return } - + // Simple age calculation (assuming current year is 2025) currentYear := 2025 age := currentYear - birthYear fmt.Printf("If you were born in %d, you are about %d years old.\n", birthYear, age) - + fmt.Println() fmt.Println("=== Simple Quiz ===") // Create a simple quiz fmt.Print("What is the capital of France? ") answer, _ := reader.ReadString('\n') answer = strings.TrimSpace(strings.ToLower(answer)) - + if answer == "paris" { fmt.Println("Correct! Well done!") } else { fmt.Println("Not quite! The answer is Paris.") } - + fmt.Println() fmt.Println("=== Yes/No Question ===") // Get a yes/no response (as text) fmt.Print("Do you like Go programming? (yes/no): ") response, _ := reader.ReadString('\n') response = strings.TrimSpace(strings.ToLower(response)) - + if response == "yes" || response == "y" { fmt.Println("Great! Go is a fantastic language!") } else { fmt.Println("That's okay, everyone has different preferences!") } - + fmt.Println() fmt.Println("=== Multiple Inputs ===") // Collect multiple pieces of information fmt.Print("What's your favorite color? ") color, _ := reader.ReadString('\n') color = strings.TrimSpace(color) - + fmt.Print("How many pets do you have? ") petStr, _ := reader.ReadString('\n') petStr = strings.TrimSpace(petStr) @@ -137,18 +137,18 @@ func main() { fmt.Println("Please enter a valid number for pets!") petCount = 0 // Default value } - + fmt.Print("What's your favorite food? ") food, _ := reader.ReadString('\n') food = strings.TrimSpace(food) - + fmt.Println() fmt.Println("=== Your Profile ===") fmt.Printf("Favorite color: %s\n", color) fmt.Printf("Number of pets: %d\n", petCount) fmt.Printf("Favorite food: %s\n", food) fmt.Printf("Thanks for sharing, %s!\n", name) - + fmt.Println() fmt.Println("=== Input Validation Example ===") // Demonstrate input validation @@ -156,7 +156,7 @@ func main() { userInput, _ := reader.ReadString('\n') userInput = strings.TrimSpace(userInput) number, err := strconv.ParseFloat(userInput, 64) - + if err != nil { fmt.Println("Invalid input! That wasn't a number.") } else if number > 0 { @@ -166,25 +166,25 @@ func main() { fmt.Println("That's not a positive number!") } } -```go +``` --- ### How to Execute 1. **Create or navigate to a Go module directory** (if not already in one): - ```bash + ``` mkdir input-example && cd input-example go mod init input - ```go + ``` 2. **Copy the code into `input.go`** 3. **Run your program**: - ```bash + ``` go run input.go - ```bash + ``` **Expected interaction:** -```go +``` === Interactive Greeting Program === What's your name? [User types their name and presses Enter] Hello, [User's name] ! Nice to meet you! @@ -199,7 +199,7 @@ What year were you born? [User enters a year] [Age calculation is performed and shown] [Additional prompts will ask for input and respond accordingly...] -```go +``` --- @@ -253,23 +253,23 @@ What year were you born? [User enters a year] ### Code Breakdown -```go +``` reader := bufio.NewReader(os.Stdin) -```go +``` - **`bufio.NewReader()`** = Creates a buffered reader for efficient input - **`os.Stdin`** = Standard input (keyboard) - **Buffered reader** = More efficient than direct input reading -```go +``` name, _ := reader.ReadString('\n') -```go +``` - **`reader.ReadString()`** = Reads input until specified delimiter - **`'\n'`** = Newline character (Enter key creates this) - **`_`** = Blank identifier to ignore error value (not ideal for production) -```go +``` name = strings.TrimSpace(name) -```go +``` - **`strings.TrimSpace()`** = Removes leading/trailing whitespace - **Important** because input includes the newline character - **Alternative**: `strings.TrimSuffix(name, "\n")` @@ -277,7 +277,7 @@ name = strings.TrimSpace(name) ### Input Processing in Go **Reading different types of input:** -```go +``` // Reading string reader := bufio.NewReader(os.Stdin) text, _ := reader.ReadString('\n') @@ -289,13 +289,13 @@ number, err := strconv.Atoi(strings.TrimSpace(input)) // Reading float input, _ := reader.ReadString('\n') number, err := strconv.ParseFloat(strings.TrimSpace(input), 64) -```go +``` ### Error Handling It's important to handle errors from input conversion: -```go +``` // Proper error handling input, err := reader.ReadString('\n') if err != nil { @@ -308,13 +308,13 @@ if err != nil { return } // Now you can safely use 'number' -```go +``` ### String Manipulation Common string operations with input: -```go +``` import "strings" // Remove whitespace @@ -328,13 +328,13 @@ parts := strings.Split(input, " ") // Check if string contains substring if strings.Contains(input, "hello") { ... } -```go +``` ### Converting Strings to Numbers Go provides several functions to convert strings to numbers: -```go +``` import "strconv" // String to integer @@ -346,26 +346,26 @@ floatVal, err := strconv.ParseFloat("123.45", 64) // float64 // String to boolean boolVal, err := strconv.ParseBool("true") // bool -```go +``` ### Alternative Input Methods **Using fmt.Scanf for formatted input:** -```go +``` var name string var age int fmt.Print("Enter name and age: ") fmt.Scanf("%s %d", &name, &age) // Reads formatted input -```go +``` **Note**: `fmt.Scanf` can be trickier to use reliably, so the bufio approach is often preferred. ### Reading a Single Character -```go +``` fmt.Print("Press any key to continue: ") char, _, _ := reader.ReadRune() // Read a single Unicode character -```go +``` ### Common Errors & Solutions @@ -379,7 +379,7 @@ char, _, _ := reader.ReadRune() // Read a single Unicode character ### Best Practices for Input **Always validate user input:** -```go +``` input, _ := reader.ReadString('\n') input = strings.TrimSpace(input) @@ -400,10 +400,10 @@ if number < 0 || number > 100 { fmt.Println("Number must be between 0 and 100!") return } -```go +``` **Handle errors properly:** -```go +``` // Always check errors, especially for number conversion number, err := strconv.Atoi(input) if err != nil { @@ -411,7 +411,7 @@ if err != nil { fmt.Println("Invalid input:", err) return // or continue with default value } -```go +``` ### Security Considerations @@ -424,7 +424,7 @@ When accepting user input: Try this full interactive program: -```go +``` package main import ( @@ -437,9 +437,9 @@ import ( func main() { reader := bufio.NewReader(os.Stdin) - + fmt.Println("=== Personal Finance Calculator ===") - + // Get user's income fmt.Print("Enter your monthly income: $") incomeStr, _ := reader.ReadString('\n') @@ -449,7 +449,7 @@ func main() { fmt.Println("Invalid income amount!") return } - + // Get expenses fmt.Print("Enter monthly rent: $") rentStr, _ := reader.ReadString('\n') @@ -459,7 +459,7 @@ func main() { fmt.Println("Invalid rent amount!") return } - + fmt.Print("Enter monthly grocery cost: $") groceriesStr, _ := reader.ReadString('\n') groceriesStr = strings.TrimSpace(groceriesStr) @@ -468,7 +468,7 @@ func main() { fmt.Println("Invalid grocery cost!") return } - + fmt.Print("Enter monthly utilities: $") utilitiesStr, _ := reader.ReadString('\n') utilitiesStr = strings.TrimSpace(utilitiesStr) @@ -477,7 +477,7 @@ func main() { fmt.Println("Invalid utilities amount!") return } - + fmt.Print("Enter monthly transportation: $") transportStr, _ := reader.ReadString('\n') transportStr = strings.TrimSpace(transportStr) @@ -486,12 +486,12 @@ func main() { fmt.Println("Invalid transportation amount!") return } - + // Calculate totals totalExpenses := rent + groceries + utilities + transportation remaining := monthlyIncome - totalExpenses savingsPercentage := (remaining / monthlyIncome) * 100 - + // Display results fmt.Println() fmt.Println("=== FINANCIAL SUMMARY ===") @@ -499,18 +499,18 @@ func main() { fmt.Printf("Total Expenses: $%.2f\n", totalExpenses) fmt.Printf("Remaining: $%.2f\n", remaining) fmt.Printf("Savings Rate: %.1f%%\n", savingsPercentage) - + if remaining > 0 { fmt.Println("Great! You're saving money each month.") } else { fmt.Println("You're spending more than you earn. Consider reducing expenses.") } } -```go +``` --- - **Excellent work! You now know how to make interactive programs that respond to user input!** + **Excellent work! You now know how to make interactive programs that respond to user input!** *Ready for the next challenge? Let's make programs that make decisions!* @@ -537,46 +537,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```go -package main - -import "fmt" - -func main() { - fmt.Println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard go conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/go/stage-1/level-5/lesson.md b/lessons/go/stage-1/level-5/lesson.md index c3d2de5..718f061 100644 --- a/lessons/go/stage-1/level-5/lesson.md +++ b/lessons/go/stage-1/level-5/lesson.md @@ -25,7 +25,7 @@ Time to make programs that can make decisions! Today you'll learn how to write c **Copy the following code into a new file called `conditionals.go`** -```go +``` package main import "fmt" @@ -219,25 +219,25 @@ func ternary(condition bool, a string, b string) string { } return b } -```go +``` --- ### How to Execute 1. **Create or navigate to a Go module directory** (if not already in one): - ```bash + ``` mkdir conditionals-example && cd conditionals-example go mod init conditionals - ```go + ``` 2. **Copy the code into `conditionals.go`** 3. **Run your program**: - ```bash + ``` go run conditionals.go - ```bash + ``` **Expected output:** -```go +``` === Simple Age Check === You are an adult (18 or older) @@ -270,7 +270,7 @@ Good job! === Switch with Expressions === Grade: B+ Score: 88, Result: Pass -```go +``` --- @@ -331,19 +331,19 @@ In Go conditionals, you'll use these comparison operators: ### Code Breakdown -```go +``` if age >= 18 { fmt.Println("You are an adult (18 or older)") } else { fmt.Println("You are a minor (under 18)") } -```go +``` - **`if`** = Start of conditional statement - **`age >= 18`** = Condition that evaluates to true or false - **`{}`** = Code block executed if condition is true - **`else`** = Code block executed if condition is false -```go +``` if grade >= 90 { fmt.Println("Grade: A (90-100)") } else if grade >= 80 { @@ -355,18 +355,18 @@ if grade >= 90 { } else { fmt.Println("Grade: F (below 60)") } -```go +``` - **`else if`** = Additional condition to check if the first was false - **Execution order** matters: Go checks each condition in order and executes the first true one - **Only one block** executes, not multiple blocks -```go +``` if username == "admin" && password == "secret123" { fmt.Println("Login successful! Welcome, admin.") } else { fmt.Println("Login failed! Invalid username or password.") } -```go +``` - **`&&`** = Logical AND operator (both conditions must be true) - **`==`** = Equality comparison operator - **Security** considerations: Never hardcode credentials in real programs @@ -374,13 +374,13 @@ if username == "admin" && password == "secret123" { ### Comparison Operators Deep Dive **Equality vs Assignment:** -```go +``` // Wrong! This assigns a value (would cause a compilation error) if username = "admin" { // ERROR: Cannot use assignment in condition // Correct! This compares values if username == "admin" { // OK: Equality comparison -```go +``` ### Logical Operators @@ -391,7 +391,7 @@ if username == "admin" { // OK: Equality comparison | NOT | `!` | Reverse condition | `!true` | `false` | **More Examples:** -```go +``` // AND: All conditions must be true age := 21 hasID := true @@ -413,11 +413,11 @@ isLoggedIn := false if !isLoggedIn { fmt.Println("Please log in first") } -```go +``` ### Nested Conditionals -```go +``` if number > 0 { fmt.Println("The number is positive") if number%2 == 0 { // Nested if @@ -427,13 +427,13 @@ if number > 0 { } } } -```go +``` - **Inner condition** only evaluated if outer condition is true - **Be careful** with nesting - too deep can be hard to read ### Switch Statement -```go +``` switch dayOfWeek { case 1: fmt.Println("Today is Monday") @@ -442,7 +442,7 @@ case 2: default: // Executes if no case matches fmt.Println("Invalid day number") } -```go +``` - **Alternative to long if/else if** chains - **Automatic break** after each case (no fallthrough by default) - **`default`** = Catch-all case when no others match @@ -451,7 +451,7 @@ default: // Executes if no case matches ### Switch Variations **Multiple values in one case:** -```go +``` grade := "A" switch grade { case "A", "A+", "A-": // Multiple values @@ -459,10 +459,10 @@ case "A", "A+", "A-": // Multiple values case "B", "B+": fmt.Println("Good!") } -```go +``` **Switch without expression (like if/else if):** -```go +``` score := 88 switch { case score >= 90: @@ -474,13 +474,13 @@ case score >= 70: default: fmt.Println("F grade") } -```go +``` ### Go's Logical Short-Circuiting Go uses short-circuit evaluation for `&&` and `||`: -```go +``` // With &&, if the first condition is false, the second is not evaluated if x != 0 && 10/x > 2 { // If x is 0, 10/x is never evaluated (no division by zero) fmt.Println("This is safe!") @@ -490,13 +490,13 @@ if x != 0 && 10/x > 2 { // If x is 0, 10/x is never evaluated (no division by z if x == 0 || 10/x > 2 { // If x is 0, 10/x is never evaluated fmt.Println("This is also safe!") } -```go +``` ### No Ternary Operator in Go Unlike many languages, Go doesn't have a ternary operator (`condition ? a : b`). Instead, use if/else or a function: -```go +``` // Instead of: result = condition ? value1 : value2 var result string if condition { @@ -512,7 +512,7 @@ func ternary(condition bool, a string, b string) string { } return b } -```go +``` ### Common Errors & Solutions @@ -539,7 +539,7 @@ Wait, let me correct that last point - Go doesn't require parentheses around con ### Best Practices for Conditionals **Use descriptive variable names:** -```go +``` // Good if isAdult { ... } if isValidEmail { ... } @@ -547,17 +547,17 @@ if isValidEmail { ... } // Avoid if x { ... } if flag { ... } -```go +``` **Keep conditions simple:** -```go +``` // Good - store complex condition in variable canVote := age >= 18 && isCitizen && !isInPrison if canVote { ... } // Avoid - hard to read if age >= 18 && isCitizen && !isInPrison { ... } -```go +``` **Consider switch vs if/else if:** - Use `switch` for exact value matching @@ -567,7 +567,7 @@ if age >= 18 && isCitizen && !isInPrison { ... } Try this complex conditional program: -```go +``` package main import "fmt" @@ -640,11 +640,11 @@ func main() { fmt.Println("Not eligible for graduation, must repeat course") } } -```go +``` --- - **Excellent work! You now understand how to make your programs make intelligent decisions!** + **Excellent work! You now understand how to make your programs make intelligent decisions!** *Ready for the next challenge? Let's learn about loops and repetition!* @@ -671,46 +671,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```go -package main - -import "fmt" - -func main() { - fmt.Println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard go conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/go/stage-1/level-6/lesson.md b/lessons/go/stage-1/level-6/lesson.md index 3f62f5f..959fc34 100644 --- a/lessons/go/stage-1/level-6/lesson.md +++ b/lessons/go/stage-1/level-6/lesson.md @@ -25,7 +25,7 @@ Time to make your programs repeat actions! Today you'll learn how to write code **Copy the following code into a new file called `loops.go`** -```go +``` package main import "fmt" @@ -172,25 +172,25 @@ func main() { } } } -```go +``` --- ### How to Execute 1. **Create or navigate to a Go module directory** (if not already in one): - ```bash + ``` mkdir loops-example && cd loops-example go mod init loops - ```go + ``` 2. **Copy the code into `loops.go`** 3. **Run your program**: - ```bash + ``` go run loops.go - ```bash + ``` **Expected output:** -```go +``` === For Loop - Counting === Count: 1 Count: 2 @@ -209,7 +209,7 @@ Countdown: 4 Countdown: 3 Countdown: 2 Countdown: 1 -Blast off! +Blast off! === For Loop - Even Numbers === Even number: 2 @@ -276,16 +276,16 @@ height: 175 score: 100 === Nested Loops - Multiplication Table === -1 2 3 -2 4 6 -3 6 9 +1 2 3 +2 4 6 +3 6 9 === Pattern - Stars === -* -* * -* * * -* * * * -* * * * * +* +* * +* * * +* * * * +* * * * * === Looping Through String Characters === Position 0: G (rune: 71) @@ -297,7 +297,7 @@ Infinite loop iteration 1 Infinite loop iteration 2 Infinite loop iteration 3 Breaking out of infinite loop -```go +``` --- @@ -348,11 +348,11 @@ Breaking out of infinite loop ### Code Breakdown -```go +``` for i := 1; i <= 5; i++ { fmt.Println("Count:", i) } -```go +``` - **`for`** = Loop keyword (Go's only loop type) - **`i := 1`** = Initialization: set up the counter variable - **`i <= 5`** = Condition: keep looping while this is true @@ -360,12 +360,12 @@ for i := 1; i <= 5; i++ { - **`{}`** = Code block that runs each iteration - **Loop execution**: 1, 2, 3, 4, 5 (stops when i becomes 6) -```go +``` for count <= 5 { fmt.Println("While count:", count) count++ } -```go +``` - **Go doesn't have** while loops, but this for loop acts like one - **No initialization or increment part** - just the condition - **Condition checked first** before each iteration @@ -373,7 +373,7 @@ for count <= 5 { ### For Loop Variations **Different increment patterns:** -```go +``` // Count by 5s for i := 0; i <= 25; i += 5 { fmt.Println(i) // 0, 5, 10, 15, 20, 25 @@ -390,13 +390,13 @@ for { // ... some condition // if someCondition { break } } -```go +``` ### Range Loop Go's `range` is a special loop for iterating over collections: -```go +``` // For slices/arrays fruits := []string{"apple", "banana", "orange"} for index, fruit := range fruits { @@ -417,49 +417,49 @@ text := "Go" for i, char := range text { fmt.Printf("Position %d: %c\n", i, char) } -```go +``` **Using blank identifier (`_`)** to ignore the index: -```go +``` for _, value := range collection { // Only care about values, not indices fmt.Println(value) } -```go +``` ### Break and Continue **`break`** = Exits the loop completely: -```go +``` for i := 1; i <= 10; i++ { if i == 5 { break // Loop stops here } fmt.Println(i) // Prints: 1, 2, 3, 4 } -```go +``` **`continue`** = Skips the rest of current iteration: -```go +``` for i := 1; i <= 5; i++ { if i == 3 { continue // Skip to next iteration } fmt.Println(i) // Prints: 1, 2, 4, 5 (skips 3) } -```go +``` ### Nested Loops -```go +``` for i := 1; i <= 3; i++ { // Outer loop for j := 1; j <= 3; j++ { // Inner loop fmt.Printf("i=%d, j=%d\n", i, j) } } -```go +``` **Output:** -```go +``` i=1, j=1 i=1, j=2 i=1, j=3 @@ -469,7 +469,7 @@ i=2, j=3 i=3, j=1 i=3, j=2 i=3, j=3 -```go +``` - **Inner loop** completes all iterations for each outer loop iteration - **Total iterations**: 3 × 3 = 9 @@ -477,17 +477,17 @@ i=3, j=3 When iterating over strings, Go uses runes (Unicode code points): -```go +``` text := "Hello" for i, char := range text { fmt.Printf("Index: %d, Character: %c, Rune: %d\n", i, char, char) } -```go +``` ### Loop Performance Considerations **Minimize work in loops:** -```go +``` // Avoid: Calculating the same thing every iteration items := []string{"a", "b", "c"} for i := 0; i < len(items); i++ { // len() called every time @@ -500,15 +500,15 @@ n := len(items) // Calculate once for i := 0; i < n; i++ { // Use pre-calculated value fmt.Println(items[i]) } -```go +``` **Prefer range loops for collections:** -```go +``` // Range is more idiomatic and often more efficient for _, item := range items { fmt.Println(item) } -```go +``` ### Common Errors & Solutions @@ -543,7 +543,7 @@ for _, item := range items { Try this complex loop program: -```go +``` package main import ( @@ -558,7 +558,7 @@ func main() { fmt.Println("Prime numbers from 2 to 30:") for num := 2; num <= 30; num++ { isPrime := true - + // Check if num is divisible by any number from 2 to sqrt(num) for divisor := 2; divisor <= int(math.Sqrt(float64(num))); divisor++ { if num%divisor == 0 { @@ -566,7 +566,7 @@ func main() { break // Found a divisor, not prime } } - + if isPrime { fmt.Printf("%d is prime\n", num) } @@ -608,11 +608,11 @@ func main() { fmt.Println(row) } } -```go +``` --- - **Excellent work! You now understand how to repeat actions efficiently with loops!** + **Excellent work! You now understand how to repeat actions efficiently with loops!** *Ready for the next challenge? Let's learn about functions - the building blocks of reusable code!* @@ -639,46 +639,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```go -package main - -import "fmt" - -func main() { - fmt.Println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard go conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/go/stage-1/level-7/lesson.md b/lessons/go/stage-1/level-7/lesson.md index ef31900..470a279 100644 --- a/lessons/go/stage-1/level-7/lesson.md +++ b/lessons/go/stage-1/level-7/lesson.md @@ -26,7 +26,7 @@ Welcome to the world of functions! Today you'll learn how to organize your code **Copy the following code into a new file called `functions.go`** -```go +``` package main import "fmt" @@ -151,7 +151,7 @@ func main() { multiply := func(a, b int) int { return a * b } - + result := multiply(4, 5) fmt.Printf("4 * 5 = %d\n", result) @@ -159,7 +159,7 @@ func main() { func() { fmt.Println("This anonymous function runs immediately!") }() - + fmt.Println() fmt.Println("=== Practical Function Examples ===") rectangleArea := calculateAreaRectangle(10, 5) @@ -189,25 +189,25 @@ func formatFullName(firstName, lastName string) string { func isNumberEven(number int) bool { return number%2 == 0 } -```go +``` --- ### How to Execute 1. **Create or navigate to a Go module directory** (if not already in one): - ```bash + ``` mkdir functions-example && cd functions-example go mod init functions - ```go + ``` 2. **Copy the code into `functions.go`** 3. **Run your program**: - ```bash + ``` go run functions.go - ```bash + ``` **Expected output:** -```go +``` === Basic Function Definition === Hello! Welcome to the wonderful world of functions! Hello! Welcome to the wonderful world of functions! @@ -251,7 +251,7 @@ Rectangle area (10 x 5): 50 Circle area (radius 7): 153.94 Full name: John Doe Is 12 even? true -```go +``` --- @@ -304,39 +304,39 @@ Is 12 even? true ### Code Breakdown -```go +``` func greetUser() { fmt.Println("Hello! Welcome to the wonderful world of functions!") } -```go +``` - **`func`** = Keyword to declare a function - **`greetUser`** = Function name (follows Go naming conventions) - **`()`** = Parameters (empty because no parameters needed) - **`{}`** = Function body (code that runs when function is called) - **No return** = Function runs code but doesn't return a value -```go +``` func greetByName(name string) { fmt.Printf("Hello, %s! Nice to meet you!\n", name) } -```go +``` - **`name string`** = Parameter (name is the variable, string is the type) - **Parameters** = Variables defined in function signature with their types - **Arguments** = Actual values passed when calling the function -```go +``` func addNumbers(a int, b int) int { sum := a + b return sum } -```go +``` - **`a int, b int`** = Multiple parameters with types - **`int`** after parameters = Return type - **`return`** = Sends value back to caller -```go +``` result1 := addNumbers(5, 3) -```go +``` - **`addNumbers(5, 3)`** = Function call with arguments - **`5` and `3`** = Arguments passed to the function - **Return value** = Value that function sends back @@ -345,25 +345,25 @@ result1 := addNumbers(5, 3) ### Function Declaration Syntax **Basic function:** -```go +``` func functionName(paramName paramType) returnType { // function body return value // if function returns something } -```go +``` **Multiple parameters of same type:** -```go +``` func add(a, b int) int { // a and b are both integers return a + b } -```go +``` ### Multiple Return Values Go's unique feature - functions can return multiple values: -```go +``` func divide(a, b float64) (float64, float64) { if b == 0 { return 0, 0 // return 2 values @@ -373,18 +373,18 @@ func divide(a, b float64) (float64, float64) { // Usage quotient, remainder := divide(10, 3) -```go +``` **Ignoring return values with blank identifier:** -```go +``` onlyQuotient, _ := divide(10, 3) // Ignore the remainder -```go +``` ### Named Return Values Go allows you to name return values in the function signature: -```go +``` func calculate(a, b int) (sum int, diff int) { sum = a + b // Direct assignment to return variable diff = a - b // Direct assignment to return variable @@ -397,13 +397,13 @@ func calculate(a, b int) (int, int) { diff := a - b return sum, diff } -```go +``` ### Variadic Functions Functions that accept a variable number of arguments: -```go +``` func sum(numbers ...int) int { // ...int means 0 or more int arguments total := 0 for _, num := range numbers { @@ -416,18 +416,18 @@ func sum(numbers ...int) int { // ...int means 0 or more int arguments fmt.Println(sum(1, 2, 3)) // 6 fmt.Println(sum(1, 2, 3, 4, 5)) // 15 fmt.Println(sum()) // 0 -```go +``` **Passing a slice to variadic function:** -```go +``` nums := []int{1, 2, 3, 4, 5} result := sum(nums...) // Note the ... to unpack the slice -```go +``` ### Function Scope **Package level:** -```go +``` var globalVar = "I'm accessible everywhere in the package" func myFunc() { @@ -436,13 +436,13 @@ func myFunc() { fmt.Println(localVar) // OK: Accessing local variable } // fmt.Println(localVar) // Error: localVar is not accessible here -```go +``` ### Anonymous Functions Functions without a name, often used as values: -```go +``` // Assign function to variable multiply := func(a, b int) int { return a * b @@ -453,13 +453,13 @@ result := multiply(5, 3) // Use like a regular function result := func(x int) int { return x * 2 }(5) // Function is called immediately with argument 5 -```go +``` ### First-Class Functions In Go, functions are first-class values: -```go +``` // Function that takes another function as parameter func process(numbers []int, operation func(int) int) []int { result := make([]int, len(numbers)) @@ -472,13 +472,13 @@ func process(numbers []int, operation func(int) int) []int { // Usage numbers := []int{1, 2, 3, 4, 5} doubled := process(numbers, func(n int) int { return n * 2 }) -```go +``` ### Error Handling Pattern A common Go pattern returns a value and an error: -```go +``` func divide(a, b float64) (float64, error) { if b == 0 { return 0, errors.New("division by zero") @@ -493,7 +493,7 @@ if err != nil { return } fmt.Println("Result:", result) -```go +``` ### Common Errors & Solutions @@ -508,7 +508,7 @@ fmt.Println("Result:", result) ### Function Best Practices **Function naming:** -```go +``` // Good - clear and descriptive func calculateArea(length, width float64) float64 { ... } func isEmailValid(email string) bool { ... } @@ -516,7 +516,7 @@ func sendNotification(message string) error { ... } // Go naming conventions: use MixedCaps (camelCase starting with capital) func CalculateArea(length, width float64) float64 { ... } // For exportable functions -```go +``` **Function size:** - Keep functions focused on a single task @@ -524,7 +524,7 @@ func CalculateArea(length, width float64) float64 { ... } // For exportable fun - If a function gets too long, consider breaking it into smaller ones **Single Responsibility Principle:** -```go +``` // Good - one purpose func calculateTax(amount, rate float64) float64 { return amount * rate @@ -537,10 +537,10 @@ func processOrder(order Order) (float64, error) { // ... other processing return total, nil } -```go +``` **Error handling in functions:** -```go +``` import "errors" func divide(a, b float64) (float64, error) { @@ -549,13 +549,13 @@ func divide(a, b float64) (float64, error) { } return a / b, nil } -```go +``` ### Advanced Challenge (For the Brave!) Try this comprehensive function example: -```go +``` package main import ( @@ -608,14 +608,14 @@ func deposit(account *Account, amount float64) error { if amount <= 0 { return errors.New("deposit amount must be positive") } - + account.Balance += amount account.History = append(account.History, Transaction{ Type: "deposit", Amount: amount, BalanceAfter: account.Balance, }) - + fmt.Printf("$%.2f deposited. New balance: $%.2f\n", amount, account.Balance) return nil } @@ -625,18 +625,18 @@ func withdraw(account *Account, amount float64) error { if amount <= 0 { return errors.New("withdrawal amount must be positive") } - + if amount > account.Balance { return errors.New("insufficient funds") } - + account.Balance -= amount account.History = append(account.History, Transaction{ Type: "withdrawal", Amount: amount, BalanceAfter: account.Balance, }) - + fmt.Printf("$%.2f withdrawn. New balance: $%.2f\n", amount, account.Balance) return nil } @@ -656,15 +656,15 @@ func transfer(fromAccount, toAccount *Account, amount float64) error { deposit(fromAccount, amount) // Attempt to reverse return fmt.Errorf("transfer failed: %v", err) } - fmt.Printf("Transfer of $%.2f from %s to %s completed!\n", + fmt.Printf("Transfer of $%.2f from %s to %s completed!\n", amount, fromAccount.Name, toAccount.Name) return nil } -```go +``` --- - **Excellent work! You now understand how to organize code using functions - a fundamental skill for all programmers!** + **Excellent work! You now understand how to organize code using functions - a fundamental skill for all programmers!** *This completes Stage 1 of Go learning! You've mastered the fundamentals of Go programming. Great job!* @@ -691,46 +691,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```go -package main - -import "fmt" - -func main() { - fmt.Println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard go conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/go/stage-2/level-1/lesson.md b/lessons/go/stage-2/level-1/lesson.md index 35e76ad..a552352 100644 --- a/lessons/go/stage-2/level-1/lesson.md +++ b/lessons/go/stage-2/level-1/lesson.md @@ -26,7 +26,7 @@ Welcome to Stage 2! You've mastered copying code - now it's time to think like a **Pseudocode** is a way to write programming logic in plain English (or your native language) before writing actual code. It's like writing a recipe or instructions for a task. **Example:** -```go +``` Algorithm: Make a sandwich 1. Get bread from pantry 2. Get peanut butter from fridge @@ -35,7 +35,7 @@ Algorithm: Make a sandwich 5. Spread jelly on the other bread slice 6. Put slices together 7. Enjoy your sandwich! -```go +``` This is much easier to understand than trying to write code first! @@ -51,25 +51,25 @@ This is much easier to understand than trying to write code first! ### How to Run 1. **Run the code**: - ```bash + ``` go run hello.go - ```go + ``` **Expected output:** -```go +``` Hello, World! -```go +``` ## Algorithm 1: Greeting Program **Pseudocode:** -```go +``` Algorithm: Display Personal Greeting 1. Display "Hello! What's your name?" to the user 2. Get the user's name from input 3. Display "Nice to meet you, " followed by the user's name 4. Display "Welcome to programming!" -```go +``` **Your Task:** Create a Go program that follows these exact steps. @@ -78,7 +78,7 @@ Algorithm: Display Personal Greeting ## Algorithm 2: Simple Calculator **Pseudocode:** -```go +``` Algorithm: Add Two Numbers 1. Ask user for first number 2. Get first number from user @@ -86,7 +86,7 @@ Algorithm: Add Two Numbers 4. Get second number from user 5. Calculate sum of the two numbers 6. Display "The sum is: " followed by the sum -```go +``` **Your Task:** Create a Go program that implements this calculator. @@ -95,14 +95,14 @@ Algorithm: Add Two Numbers ## Algorithm 3: Age Calculator **Pseudocode:** -```go +``` Algorithm: Calculate Age in Days 1. Display "Enter your age in years: " 2. Get age in years from user 3. Calculate days = age × 365 4. Display "You are approximately " + days + " days old" 5. Display "That's a lot of days!" -```go +``` **Your Task:** Create a program that calculates approximate age in days. @@ -111,7 +111,7 @@ Algorithm: Calculate Age in Days ## Algorithm 4: Temperature Converter **Pseudocode:** -```go +``` Algorithm: Celsius to Fahrenheit Converter 1. Display "Enter temperature in Celsius: " 2. Get temperature in Celsius from user @@ -120,7 +120,7 @@ Algorithm: Celsius to Fahrenheit Converter 5. Display "°C = " 6. Display the Fahrenheit temperature 7. Display "°F" -```go +``` **Your Task:** Create a temperature conversion program. @@ -129,7 +129,7 @@ Algorithm: Celsius to Fahrenheit Converter ## Algorithm 5: Rectangle Area Calculator **Pseudocode:** -```go +``` Algorithm: Calculate Rectangle Area 1. Display "Rectangle Area Calculator" 2. Display "Enter length: " @@ -140,7 +140,7 @@ Algorithm: Calculate Rectangle Area 7. Calculate perimeter = 2 × (length + width) 8. Display "Area: " + area 9. Display "Perimeter: " + perimeter -```go +``` **Your Task:** Create a program that calculates both area and perimeter. @@ -149,7 +149,7 @@ Algorithm: Calculate Rectangle Area ## Algorithm 6: Simple Interest Calculator **Pseudocode:** -```go +``` Algorithm: Calculate Simple Interest 1. Display "Simple Interest Calculator" 2. Display "Enter principal amount: $" @@ -163,7 +163,7 @@ Algorithm: Calculate Simple Interest 10. Display "Principal: $" + principal 11. Display "Interest: $" + interest 12. Display "Total: $" + total -```go +``` **Your Task:** Implement the complete interest calculation. @@ -172,7 +172,7 @@ Algorithm: Calculate Simple Interest ## Algorithm 7: BMI Calculator **Pseudocode:** -```go +``` Algorithm: Calculate Body Mass Index 1. Display "BMI Calculator" 2. Display "Enter weight in kg: " @@ -189,7 +189,7 @@ Algorithm: Calculate Body Mass Index Display "Category: Overweight" 11. Else Display "Category: Obesity" -```go +``` **Your Task:** Create a program that calculates BMI with categorization. @@ -248,7 +248,7 @@ Algorithm: Calculate Body Mass Index ## Pseudocode Best Practices ### Good Pseudocode -```go +``` Algorithm: Process User Data 1. Get user's name 2. Get user's age @@ -257,18 +257,18 @@ Algorithm: Process User Data Else Display "Minor user" 4. Display "Data processed" -```go +``` ### Bad Pseudocode (Too Vague) -```go +``` Algorithm: Do stuff 1. Get things 2. Calculate something 3. Show results -```go +``` ### Good Pseudocode (Clear and Specific) -```go +``` Algorithm: Calculate BMI 1. Display "BMI Calculator" 2. Display "Enter weight in kg: " @@ -277,7 +277,7 @@ Algorithm: Calculate BMI 5. Get height from user 6. Calculate BMI = weight ÷ (height × height) 7. Display "Your BMI is: " + BMI -```go +``` --- @@ -289,7 +289,7 @@ Algorithm: Calculate BMI ### Algorithm 1: Greeting Program -```go +``` package main import ( @@ -301,25 +301,25 @@ import ( func main() { reader := bufio.NewReader(os.Stdin) - + fmt.Println("Algorithm 1: Greeting Program") - + // Display "Hello! What's your name?" to the user fmt.Print("Hello! What's your name? ") name, _ := reader.ReadString('\n') name = strings.TrimSpace(name) - + // Display "Nice to meet you, " followed by the user's name fmt.Println("Nice to meet you, " + name) - + // Display "Welcome to programming!" fmt.Println("Welcome to programming!") } -```go +``` ### Algorithm 2: Simple Calculator -```go +``` package main import ( @@ -332,9 +332,9 @@ import ( func main() { reader := bufio.NewReader(os.Stdin) - + fmt.Println("Algorithm 2: Simple Calculator") - + // Ask user for first number fmt.Print("Enter first number: ") firstInput, _ := reader.ReadString('\n') @@ -343,7 +343,7 @@ func main() { fmt.Println("Invalid number entered!") return } - + // Ask user for second number fmt.Print("Enter second number: ") secondInput, _ := reader.ReadString('\n') @@ -352,18 +352,18 @@ func main() { fmt.Println("Invalid number entered!") return } - + // Calculate sum of the two numbers sum := firstNum + secondNum - + // Display "The sum is: " followed by the sum fmt.Println("The sum is: " + fmt.Sprintf("%g", sum)) } -```go +``` ### Algorithm 3: Age Calculator -```go +``` package main import ( @@ -376,9 +376,9 @@ import ( func main() { reader := bufio.NewReader(os.Stdin) - + fmt.Println("Algorithm 3: Age Calculator") - + // Display "Enter your age in years: " fmt.Print("Enter your age in years: ") ageInput, _ := reader.ReadString('\n') @@ -387,19 +387,19 @@ func main() { fmt.Println("Invalid number entered!") return } - + // Calculate days = age × 365 days := age * 365 - + // Display messages fmt.Println("You are approximately " + strconv.Itoa(days) + " days old") fmt.Println("That's a lot of days!") } -```go +``` ### Algorithm 4: Temperature Converter -```go +``` package main import ( @@ -412,9 +412,9 @@ import ( func main() { reader := bufio.NewReader(os.Stdin) - + fmt.Println("Algorithm 4: Temperature Converter") - + // Display "Enter temperature in Celsius: " fmt.Print("Enter temperature in Celsius: ") celsiusInput, _ := reader.ReadString('\n') @@ -423,18 +423,18 @@ func main() { fmt.Println("Invalid number entered!") return } - + // Calculate Fahrenheit = (Celsius × 9/5) + 32 fahrenheit := (celsius * 9/5) + 32 - + // Display the results fmt.Printf("%.2f°C = %.2f°F\n", celsius, fahrenheit) } -```go +``` ### Algorithm 5: Rectangle Area Calculator -```go +``` package main import ( @@ -447,9 +447,9 @@ import ( func main() { reader := bufio.NewReader(os.Stdin) - + fmt.Println("Rectangle Area Calculator") - + // Get length from user fmt.Print("Enter length: ") lengthInput, _ := reader.ReadString('\n') @@ -458,7 +458,7 @@ func main() { fmt.Println("Invalid number entered!") return } - + // Get width from user fmt.Print("Enter width: ") widthInput, _ := reader.ReadString('\n') @@ -467,22 +467,22 @@ func main() { fmt.Println("Invalid number entered!") return } - + // Calculate area = length × width area := length * width - + // Calculate perimeter = 2 × (length + width) perimeter := 2 * (length + width) - + // Display results fmt.Println("Area: " + fmt.Sprintf("%g", area)) fmt.Println("Perimeter: " + fmt.Sprintf("%g", perimeter)) } -```go +``` ### Algorithm 6: Simple Interest Calculator -```go +``` package main import ( @@ -495,9 +495,9 @@ import ( func main() { reader := bufio.NewReader(os.Stdin) - + fmt.Println("Simple Interest Calculator") - + // Get principal from user fmt.Print("Enter principal amount: $") principalInput, _ := reader.ReadString('\n') @@ -506,7 +506,7 @@ func main() { fmt.Println("Invalid number entered!") return } - + // Get rate from user fmt.Print("Enter interest rate (%): ") rateInput, _ := reader.ReadString('\n') @@ -515,7 +515,7 @@ func main() { fmt.Println("Invalid number entered!") return } - + // Get time from user fmt.Print("Enter time in years: ") timeInput, _ := reader.ReadString('\n') @@ -524,23 +524,23 @@ func main() { fmt.Println("Invalid number entered!") return } - + // Calculate interest = (principal × rate × time) ÷ 100 interest := (principal * rate * time) / 100 - + // Calculate total = principal + interest total := principal + interest - + // Display results fmt.Printf("Principal: $%.2f\n", principal) fmt.Printf("Interest: $%.2f\n", interest) fmt.Printf("Total: $%.2f\n", total) } -```go +``` ### Algorithm 7: BMI Calculator -```go +``` package main import ( @@ -553,9 +553,9 @@ import ( func main() { reader := bufio.NewReader(os.Stdin) - + fmt.Println("BMI Calculator") - + // Get weight from user fmt.Print("Enter weight in kg: ") weightInput, _ := reader.ReadString('\n') @@ -564,7 +564,7 @@ func main() { fmt.Println("Invalid number entered!") return } - + // Get height from user fmt.Print("Enter height in meters: ") heightInput, _ := reader.ReadString('\n') @@ -573,13 +573,13 @@ func main() { fmt.Println("Invalid number entered!") return } - + // Calculate bmi = weight ÷ (height × height) bmi := weight / (height * height) - + // Display the BMI fmt.Printf("Your BMI is: %.2f\n", bmi) - + // Category determination if bmi < 18.5 { fmt.Println("Category: Underweight") @@ -591,7 +591,7 @@ func main() { fmt.Println("Category: Obesity") } } -```go +``` ### Common Translation Patterns @@ -636,29 +636,29 @@ func main() { ### Input/Output Patterns **Getting Numbers:** -```go +``` fmt.Print("Enter age: ") input, _ := reader.ReadString('\n') age, err := strconv.Atoi(strings.TrimSpace(input)) -```go +``` **Getting Text:** -```go +``` fmt.Print("Enter name: ") input, _ := reader.ReadString('\n') name := strings.TrimSpace(input) -```go +``` **Displaying Results:** -```go +``` fmt.Println("Result: " + result) fmt.Printf("Price: $%.2f\n", price) fmt.Println("Hello, " + name + "!") -```go +``` --- - **Congratulations! You've translated your first pseudocode algorithms into working Go programs!** + **Congratulations! You've translated your first pseudocode algorithms into working Go programs!** *This is a major milestone - you're now thinking like a programmer! Next up: Variables in pseudocode!* @@ -678,46 +678,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```go -package main - -import "fmt" - -func main() { - fmt.Println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard go conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/go/stage-2/level-2/lesson.md b/lessons/go/stage-2/level-2/lesson.md index 4fb831e..1d4dffe 100644 --- a/lessons/go/stage-2/level-2/lesson.md +++ b/lessons/go/stage-2/level-2/lesson.md @@ -26,25 +26,25 @@ Welcome to Level 2! Today we're focusing on how to handle variables in your pseu Variables in pseudocode follow simple patterns: **Declaration and assignment:** -```go +``` SET name TO "John" SET age TO 25 SET is_student TO TRUE -```go +``` **Reassignment:** -```go +``` SET age TO age + 1 SET total TO total + new_value SET is_student TO FALSE -```go +``` **Calculations with variables:** -```go +``` SET area TO length * width SET average TO (num1 + num2 + num3) / 3 SET is_adult TO age >= 18 -```go +``` --- @@ -58,19 +58,19 @@ SET is_adult TO age >= 18 ### How to Run 1. **Run the code**: - ```bash + ``` go run hello.go - ```go + ``` **Expected output:** -```go +``` Hello, World! -```go +``` ## Algorithm 1: Simple Variable Swapping **Pseudocode:** -```go +``` Algorithm: Swap Two Variables 1. SET first_number TO 10 2. SET second_number TO 20 @@ -79,7 +79,7 @@ Algorithm: Swap Two Variables 5. SET first_number TO second_number 6. SET second_number TO temp 7. DISPLAY "After swap: first=" + first_number + ", second=" + second_number -```go +``` **Your Task:** Create a Go program that demonstrates variable swapping. @@ -88,7 +88,7 @@ Algorithm: Swap Two Variables ## Algorithm 2: Running Total Calculator **Pseudocode:** -```go +``` Algorithm: Calculate Running Total 1. SET total TO 0 2. SET count TO 0 @@ -105,7 +105,7 @@ Algorithm: Calculate Running Total 13. DISPLAY "Total: " + total 14. DISPLAY "Count: " + count 15. DISPLAY "Average: " + average -```go +``` **Your Task:** Create a Go program that calculates a running total and average. @@ -114,7 +114,7 @@ Algorithm: Calculate Running Total ## Algorithm 3: Temperature Tracker **Pseudocode:** -```go +``` Algorithm: Track Temperature Readings 1. SET min_temp TO 100 2. SET max_temp TO -100 @@ -136,7 +136,7 @@ Algorithm: Track Temperature Readings 13. IF current_temp > max_temp THEN SET max_temp TO current_temp 14. DISPLAY "Current: " + current_temp + ", Min: " + min_temp + ", Max: " + max_temp -```go +``` **Your Task:** Create a Go program that tracks min/max temperatures. @@ -145,7 +145,7 @@ Algorithm: Track Temperature Readings ## Algorithm 4: Account Balance Tracker **Pseudocode:** -```go +``` Algorithm: Track Bank Account Balance 1. SET account_balance TO 1000 2. SET transaction_amount TO -50 @@ -160,7 +160,7 @@ Algorithm: Track Bank Account Balance 11. SET transaction_amount TO 150.25 12. SET account_balance TO account_balance + transaction_amount 13. DISPLAY "Balance after deposit: $" + account_balance -```go +``` **Your Task:** Create a Go program that tracks account balance changes. @@ -169,7 +169,7 @@ Algorithm: Track Bank Account Balance ## Algorithm 5: Student Grade Calculator **Pseudocode:** -```go +``` Algorithm: Calculate Student Grade 1. SET total_points TO 0 2. SET possible_points TO 0 @@ -195,7 +195,7 @@ Algorithm: Calculate Student Grade 22. DISPLAY "Possible Points: " + possible_points 23. DISPLAY "Percentage: " + percentage 24. DISPLAY "Letter Grade: " + letter_grade -```go +``` **Your Task:** Create a Go program that calculates student grades. @@ -204,7 +204,7 @@ Algorithm: Calculate Student Grade ## Algorithm 6: Counter Patterns **Pseudocode:** -```go +``` Algorithm: Different Counter Patterns 1. SET counter TO 1 2. SET even_counter TO 2 @@ -221,7 +221,7 @@ Algorithm: Different Counter Patterns 13. DISPLAY "Odd: " + odd_counter 14. SET odd_counter TO odd_counter + 2 15. END WHILE -```go +``` **Your Task:** Create a Go program that demonstrates different counting patterns. @@ -230,7 +230,7 @@ Algorithm: Different Counter Patterns ## Algorithm 7: Accumulator Pattern **Pseudocode:** -```go +``` Algorithm: Calculate Statistics 1. SET sum TO 0 2. SET count TO 0 @@ -252,7 +252,7 @@ Algorithm: Calculate Statistics 18. DISPLAY "Count: " + count 19. DISPLAY "Product: " + product 20. DISPLAY "Average: " + average -```go +``` **Your Task:** Create a Go program that demonstrates accumulator patterns. @@ -309,7 +309,7 @@ Algorithm: Calculate Statistics ### Algorithm 1: Simple Variable Swapping -```go +``` package main import "fmt" @@ -327,11 +327,11 @@ func main() { fmt.Println("After swap: first=" + fmt.Sprintf("%d", first_number) + ", second=" + fmt.Sprintf("%d", second_number)) } -```go +``` ### Algorithm 2: Running Total Calculator -```go +``` package main import "fmt" @@ -359,11 +359,11 @@ func main() { fmt.Println("Count: " + fmt.Sprintf("%d", count)) fmt.Println("Average: " + fmt.Sprintf("%f", average)) } -```go +``` ### Algorithm 3: Temperature Tracker -```go +``` package main import "fmt" @@ -400,11 +400,11 @@ func main() { } fmt.Println("Current: " + fmt.Sprintf("%d", current_temp) + ", Min: " + fmt.Sprintf("%d", min_temp) + ", Max: " + fmt.Sprintf("%d", max_temp)) } -```go +``` ### Algorithm 4: Account Balance Tracker -```go +``` package main import "fmt" @@ -429,11 +429,11 @@ func main() { account_balance = account_balance + transaction_amount fmt.Println("Balance after deposit: $" + fmt.Sprintf("%.2f", account_balance)) } -```go +``` ### Algorithm 5: Student Grade Calculator -```go +``` package main import "fmt" @@ -476,11 +476,11 @@ func main() { fmt.Println("Percentage: " + fmt.Sprintf("%.2f", percentage)) fmt.Println("Letter Grade: " + letter_grade) } -```go +``` ### Algorithm 6: Counter Patterns -```go +``` package main import "fmt" @@ -505,11 +505,11 @@ func main() { odd_counter = odd_counter + 2 } } -```go +``` ### Algorithm 7: Accumulator Pattern -```go +``` package main import "fmt" @@ -542,7 +542,7 @@ func main() { fmt.Println("Product: " + fmt.Sprintf("%d", product)) fmt.Println("Average: " + fmt.Sprintf("%.2f", average)) } -```go +``` ### Variable Translation Patterns @@ -565,7 +565,7 @@ func main() { --- - **Excellent work! You've mastered handling variables in pseudocode-to-code translation!** + **Excellent work! You've mastered handling variables in pseudocode-to-code translation!** *Next up: Mathematical operations in pseudocode!* @@ -585,46 +585,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```go -package main - -import "fmt" - -func main() { - fmt.Println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard go conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/go/stage-2/level-3/lesson.md b/lessons/go/stage-2/level-3/lesson.md index f537149..dc5cef4 100644 --- a/lessons/go/stage-2/level-3/lesson.md +++ b/lessons/go/stage-2/level-3/lesson.md @@ -26,36 +26,36 @@ Welcome to Level 3! Today we're focusing on mathematical operations in pseudocod Mathematical expressions in pseudocode follow standard notation: **Basic operations:** -```go +``` SET result TO 5 + 3 SET result TO 10 - 4 SET result TO 6 * 7 SET result TO 15 / 3 SET remainder TO 17 MOD 5 -```go +``` **Complex expressions:** -```go +``` SET area TO length * width SET volume TO length * width * height SET average TO (num1 + num2 + num3) / 3 SET tax TO price * 0.08 SET discount TO original_price * discount_rate -```go +``` **Order of operations:** -```go +``` SET result TO 2 + 3 * 4 // result = 14 (not 20), multiplication first SET result TO (2 + 3) * 4 // result = 20, parentheses override SET result TO 10 / 2 + 3 // result = 8, division first -```go +``` **Mathematical functions:** -```go +``` SET result TO POWER(2, 3) // 2 to the power of 3 SET result TO SQRT(16) // square root of 16 SET result TO ROUND(3.7) // round to nearest integer -```go +``` --- @@ -69,19 +69,19 @@ SET result TO ROUND(3.7) // round to nearest integer ### How to Run 1. **Run the code**: - ```bash + ``` go run hello.go - ```go + ``` **Expected output:** -```go +``` Hello, World! -```go +``` ## Algorithm 1: Complex Arithmetic Expression **Pseudocode:** -```go +``` Algorithm: Evaluate Complex Expression 1. SET a TO 10 2. SET b TO 5 @@ -92,7 +92,7 @@ Algorithm: Evaluate Complex Expression 7. DISPLAY "Result without parentheses: " + result2 8. SET result3 TO ((a + b) * c - a) / c 9. DISPLAY "Result with different grouping: " + result3 -```go +``` **Your Task:** Create a Go program that evaluates complex arithmetic expressions. @@ -101,7 +101,7 @@ Algorithm: Evaluate Complex Expression ## Algorithm 2: Quadratic Formula Calculator **Pseudocode:** -```go +``` Algorithm: Solve Quadratic Equation 1. SET a TO 1 2. SET b TO -5 @@ -112,7 +112,7 @@ Algorithm: Solve Quadratic Equation 7. SET root2 TO (-b - sqrt_discriminant) / (2 * a) 8. DISPLAY "Root 1: " + root1 9. DISPLAY "Root 2: " + root2 -```go +``` **Your Task:** Create a Go program that solves quadratic equations using the quadratic formula. @@ -121,7 +121,7 @@ Algorithm: Solve Quadratic Equation ## Algorithm 3: Compound Interest Calculator **Pseudocode:** -```go +``` Algorithm: Calculate Compound Interest 1. SET principal TO 1000 2. SET rate TO 0.05 @@ -132,7 +132,7 @@ Algorithm: Calculate Compound Interest 7. DISPLAY "Principal: $" + principal 8. DISPLAY "Final Amount: $" + amount 9. DISPLAY "Interest Earned: $" + interest -```go +``` **Your Task:** Create a Go program that calculates compound interest. @@ -141,7 +141,7 @@ Algorithm: Calculate Compound Interest ## Algorithm 4: Geometric Calculations **Pseudocode:** -```go +``` Algorithm: Calculate Geometric Properties 1. SET radius TO 5 2. SET side TO 4 @@ -155,7 +155,7 @@ Algorithm: Calculate Geometric Properties 10. DISPLAY "Circle - Area: " + circle_area + ", Circumference: " + circle_circumference 11. DISPLAY "Square - Area: " + square_area + ", Perimeter: " + square_perimeter 12. DISPLAY "Triangle - Area: " + triangle_area -```go +``` **Your Task:** Create a Go program that calculates geometric properties. @@ -164,7 +164,7 @@ Algorithm: Calculate Geometric Properties ## Algorithm 5: Physics Formula Calculator **Pseudocode:** -```go +``` Algorithm: Physics Calculations 1. SET mass TO 5.5 2. SET velocity TO 10 @@ -178,7 +178,7 @@ Algorithm: Physics Calculations 10. DISPLAY "Force: " + force 11. DISPLAY "Distance: " + distance 12. DISPLAY "Momentum: " + momentum -```go +``` **Your Task:** Create a Go program that calculates physics formulas. @@ -187,7 +187,7 @@ Algorithm: Physics Calculations ## Algorithm 6: Temperature Conversion with Multiple Formulas **Pseudocode:** -```go +``` Algorithm: Multiple Temperature Conversions 1. SET celsius TO 25 2. SET fahrenheit TO celsius * 9 / 5 + 32 @@ -199,7 +199,7 @@ Algorithm: Multiple Temperature Conversions 8. DISPLAY "Kelvin: " + kelvin 9. DISPLAY "F to C: " + celsius_from_f 10. DISPLAY "K to C: " + celsius_from_k -```go +``` **Your Task:** Create a Go program that performs multiple temperature conversions. @@ -208,7 +208,7 @@ Algorithm: Multiple Temperature Conversions ## Algorithm 7: Statistical Calculations **Pseudocode:** -```go +``` Algorithm: Calculate Statistics for Three Numbers 1. SET num1 TO 10 2. SET num2 TO 20 @@ -225,7 +225,7 @@ Algorithm: Calculate Statistics for Three Numbers 13. DISPLAY "Range: " + range 14. DISPLAY "Variance: " + variance 15. DISPLAY "Standard Deviation: " + std_deviation -```go +``` **Your Task:** Create a Go program that calculates statistical measures. @@ -281,7 +281,7 @@ Algorithm: Calculate Statistics for Three Numbers ### Algorithm 1: Complex Arithmetic Expression -```go +``` package main import "fmt" @@ -301,11 +301,11 @@ func main() { result3 := (float64(a+b)*float64(c) - float64(a)) / float64(c) fmt.Println("Result with different grouping: " + fmt.Sprintf("%f", result3)) } -```go +``` ### Algorithm 2: Quadratic Formula Calculator -```go +``` package main import ( @@ -327,11 +327,11 @@ func main() { fmt.Println("Root 1: " + fmt.Sprintf("%f", root1)) fmt.Println("Root 2: " + fmt.Sprintf("%f", root2)) } -```go +``` ### Algorithm 3: Compound Interest Calculator -```go +``` package main import ( @@ -353,11 +353,11 @@ func main() { fmt.Println("Final Amount: $" + fmt.Sprintf("%.2f", amount)) fmt.Println("Interest Earned: $" + fmt.Sprintf("%.2f", interest)) } -```go +``` ### Algorithm 4: Geometric Calculations -```go +``` package main import ( @@ -382,11 +382,11 @@ func main() { fmt.Println("Square - Area: " + fmt.Sprintf("%.2f", square_area) + ", Perimeter: " + fmt.Sprintf("%.2f", square_perimeter)) fmt.Println("Triangle - Area: " + fmt.Sprintf("%.2f", triangle_area)) } -```go +``` ### Algorithm 5: Physics Formula Calculator -```go +``` package main import "fmt" @@ -408,11 +408,11 @@ func main() { fmt.Println("Distance: " + fmt.Sprintf("%f", distance)) fmt.Println("Momentum: " + fmt.Sprintf("%f", momentum)) } -```go +``` ### Algorithm 6: Temperature Conversion with Multiple Formulas -```go +``` package main import "fmt" @@ -431,11 +431,11 @@ func main() { fmt.Println("F to C: " + fmt.Sprintf("%f", celsius_from_f)) fmt.Println("K to C: " + fmt.Sprintf("%f", celsius_from_k)) } -```go +``` ### Algorithm 7: Statistical Calculations -```go +``` package main import ( @@ -463,7 +463,7 @@ func main() { fmt.Println("Variance: " + fmt.Sprintf("%f", variance)) fmt.Println("Standard Deviation: " + fmt.Sprintf("%.2f", std_deviation)) } -```go +``` ### Mathematical Operation Translation Patterns @@ -489,7 +489,7 @@ func main() { --- - **Excellent work! You've mastered translating mathematical operations from pseudocode to Go!** + **Excellent work! You've mastered translating mathematical operations from pseudocode to Go!** *Next up: Input/Output operations in pseudocode!* @@ -509,46 +509,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```go -package main - -import "fmt" - -func main() { - fmt.Println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard go conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/go/stage-2/level-4/lesson.md b/lessons/go/stage-2/level-4/lesson.md index 1970d47..1f31aec 100644 --- a/lessons/go/stage-2/level-4/lesson.md +++ b/lessons/go/stage-2/level-4/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Go:** -```go +``` ALGORITHM: Input/Output Algorithms BEGIN @@ -39,7 +39,7 @@ BEGIN // Translate step by step into Go // Test with sample inputs END -```go +``` **Implementation Steps:** 1. Analyze what the algorithm does @@ -54,14 +54,14 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` go run hello.go - ```go + ``` **Expected output:** -```go +``` Hello, World! -```go +``` ### How to Approach This @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in Go: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```go +``` PSEUDOCODE: READ number IF number > 0 THEN @@ -168,7 +168,7 @@ PSEUDOCODE: ELSE PRINT "Not positive" END IF -```go +``` This becomes structured Go code following the language syntax. @@ -211,46 +211,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```go -package main - -import "fmt" - -func main() { - fmt.Println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard go conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/go/stage-2/level-5/lesson.md b/lessons/go/stage-2/level-5/lesson.md index faab89e..554ba97 100644 --- a/lessons/go/stage-2/level-5/lesson.md +++ b/lessons/go/stage-2/level-5/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Go:** -```go +``` ALGORITHM: Decision Algorithms BEGIN @@ -39,7 +39,7 @@ BEGIN // Translate step by step into Go // Test with sample inputs END -```go +``` **Implementation Steps:** 1. Analyze what the algorithm does @@ -54,14 +54,14 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` go run hello.go - ```go + ``` **Expected output:** -```go +``` Hello, World! -```go +``` ### How to Approach This @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in Go: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```go +``` PSEUDOCODE: READ number IF number > 0 THEN @@ -168,7 +168,7 @@ PSEUDOCODE: ELSE PRINT "Not positive" END IF -```go +``` This becomes structured Go code following the language syntax. @@ -211,46 +211,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```go -package main - -import "fmt" - -func main() { - fmt.Println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard go conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/go/stage-2/level-6/lesson.md b/lessons/go/stage-2/level-6/lesson.md index db5eb29..e4c2628 100644 --- a/lessons/go/stage-2/level-6/lesson.md +++ b/lessons/go/stage-2/level-6/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Go:** -```go +``` ALGORITHM: Loop Algorithms BEGIN @@ -39,7 +39,7 @@ BEGIN // Translate step by step into Go // Test with sample inputs END -```go +``` **Implementation Steps:** 1. Analyze what the algorithm does @@ -54,14 +54,14 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` go run hello.go - ```go + ``` **Expected output:** -```go +``` Hello, World! -```go +``` ### How to Approach This @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in Go: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```go +``` PSEUDOCODE: READ number IF number > 0 THEN @@ -168,7 +168,7 @@ PSEUDOCODE: ELSE PRINT "Not positive" END IF -```go +``` This becomes structured Go code following the language syntax. @@ -211,46 +211,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```go -package main - -import "fmt" - -func main() { - fmt.Println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard go conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/go/stage-2/level-7/lesson.md b/lessons/go/stage-2/level-7/lesson.md index 41aa6e0..0744daf 100644 --- a/lessons/go/stage-2/level-7/lesson.md +++ b/lessons/go/stage-2/level-7/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Go:** -```go +``` ALGORITHM: Function Design BEGIN @@ -39,7 +39,7 @@ BEGIN // Translate step by step into Go // Test with sample inputs END -```go +``` **Implementation Steps:** 1. Analyze what the algorithm does @@ -54,14 +54,14 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` go run hello.go - ```go + ``` **Expected output:** -```go +``` Hello, World! -```go +``` ### How to Approach This @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in Go: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```go +``` PSEUDOCODE: READ number IF number > 0 THEN @@ -168,7 +168,7 @@ PSEUDOCODE: ELSE PRINT "Not positive" END IF -```go +``` This becomes structured Go code following the language syntax. @@ -211,46 +211,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```go -package main - -import "fmt" - -func main() { - fmt.Println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard go conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/go/stage-3/level-1/lesson.md b/lessons/go/stage-3/level-1/lesson.md index 9ffe001..8de06a1 100644 --- a/lessons/go/stage-3/level-1/lesson.md +++ b/lessons/go/stage-3/level-1/lesson.md @@ -51,14 +51,14 @@ Simple Problem Analysis - Design an algorithm to solve this problem, then implem ### How to Run 1. **Run the code**: - ```bash + ``` go run hello.go - ```go + ``` **Expected output:** -```go +``` Hello, World! -```go +``` ### How to Approach This @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```go +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -169,7 +169,7 @@ BEGIN - Step 3 4. Display results END -```go +``` Then translate this directly to Go code. @@ -212,46 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```go -package main - -import "fmt" - -func main() { - fmt.Println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard go conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/go/stage-3/level-2/lesson.md b/lessons/go/stage-3/level-2/lesson.md index 1de68fa..4fa5391 100644 --- a/lessons/go/stage-3/level-2/lesson.md +++ b/lessons/go/stage-3/level-2/lesson.md @@ -51,14 +51,14 @@ Data Structure Planning - Design an algorithm to solve this problem, then implem ### How to Run 1. **Run the code**: - ```bash + ``` go run hello.go - ```go + ``` **Expected output:** -```go +``` Hello, World! -```go +``` ### How to Approach This @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```go +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -169,7 +169,7 @@ BEGIN - Step 3 4. Display results END -```go +``` Then translate this directly to Go code. @@ -212,46 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```go -package main - -import "fmt" - -func main() { - fmt.Println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard go conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/go/stage-3/level-3/lesson.md b/lessons/go/stage-3/level-3/lesson.md index 1953414..bc11a48 100644 --- a/lessons/go/stage-3/level-3/lesson.md +++ b/lessons/go/stage-3/level-3/lesson.md @@ -51,14 +51,14 @@ Mathematical Problems - Design an algorithm to solve this problem, then implemen ### How to Run 1. **Run the code**: - ```bash + ``` go run hello.go - ```go + ``` **Expected output:** -```go +``` Hello, World! -```go +``` ### How to Approach This @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```go +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -169,7 +169,7 @@ BEGIN - Step 3 4. Display results END -```go +``` Then translate this directly to Go code. @@ -212,46 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```go -package main - -import "fmt" - -func main() { - fmt.Println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard go conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/go/stage-3/level-4/lesson.md b/lessons/go/stage-3/level-4/lesson.md index 498d603..6a3ed73 100644 --- a/lessons/go/stage-3/level-4/lesson.md +++ b/lessons/go/stage-3/level-4/lesson.md @@ -51,14 +51,14 @@ Text Processing Problems - Design an algorithm to solve this problem, then imple ### How to Run 1. **Run the code**: - ```bash + ``` go run hello.go - ```go + ``` **Expected output:** -```go +``` Hello, World! -```go +``` ### How to Approach This @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```go +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -169,7 +169,7 @@ BEGIN - Step 3 4. Display results END -```go +``` Then translate this directly to Go code. @@ -212,46 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```go -package main - -import "fmt" - -func main() { - fmt.Println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard go conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/go/stage-3/level-5/lesson.md b/lessons/go/stage-3/level-5/lesson.md index 1afad55..c568df6 100644 --- a/lessons/go/stage-3/level-5/lesson.md +++ b/lessons/go/stage-3/level-5/lesson.md @@ -51,14 +51,14 @@ Logic Problems - Design an algorithm to solve this problem, then implement it. ### How to Run 1. **Run the code**: - ```bash + ``` go run hello.go - ```go + ``` **Expected output:** -```go +``` Hello, World! -```go +``` ### How to Approach This @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```go +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -169,7 +169,7 @@ BEGIN - Step 3 4. Display results END -```go +``` Then translate this directly to Go code. @@ -212,46 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```go -package main - -import "fmt" - -func main() { - fmt.Println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard go conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/go/stage-3/level-6/lesson.md b/lessons/go/stage-3/level-6/lesson.md index 0ac2e0a..09381ba 100644 --- a/lessons/go/stage-3/level-6/lesson.md +++ b/lessons/go/stage-3/level-6/lesson.md @@ -51,14 +51,14 @@ Search Algorithms - Design an algorithm to solve this problem, then implement it ### How to Run 1. **Run the code**: - ```bash + ``` go run hello.go - ```go + ``` **Expected output:** -```go +``` Hello, World! -```go +``` ### How to Approach This @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```go +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -169,7 +169,7 @@ BEGIN - Step 3 4. Display results END -```go +``` Then translate this directly to Go code. @@ -212,46 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```go -package main - -import "fmt" - -func main() { - fmt.Println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard go conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/go/stage-3/level-7/lesson.md b/lessons/go/stage-3/level-7/lesson.md index a7d5f54..1cacb54 100644 --- a/lessons/go/stage-3/level-7/lesson.md +++ b/lessons/go/stage-3/level-7/lesson.md @@ -51,14 +51,14 @@ Sorting Algorithms - Design an algorithm to solve this problem, then implement i ### How to Run 1. **Run the code**: - ```bash + ``` go run hello.go - ```go + ``` **Expected output:** -```go +``` Hello, World! -```go +``` ### How to Approach This @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```go +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -169,7 +169,7 @@ BEGIN - Step 3 4. Display results END -```go +``` Then translate this directly to Go code. @@ -212,46 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```go -package main - -import "fmt" - -func main() { - fmt.Println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard go conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/go/stage-4/level-1/lesson.md b/lessons/go/stage-4/level-1/lesson.md index 7f077fe..a147802 100644 --- a/lessons/go/stage-4/level-1/lesson.md +++ b/lessons/go/stage-4/level-1/lesson.md @@ -51,14 +51,14 @@ Build a complete Calculator Application application that: ### How to Run 1. **Run the code**: - ```bash + ``` go run hello.go - ```go + ``` **Expected output:** -```go +``` Hello, World! -```go +``` ### How to Approach This @@ -158,13 +158,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```go +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```go +``` Build incrementally - get one feature working before adding the next. @@ -207,46 +207,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```go -package main - -import "fmt" - -func main() { - fmt.Println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard go conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/go/stage-4/level-2/lesson.md b/lessons/go/stage-4/level-2/lesson.md index 3f296b4..b0e3f00 100644 --- a/lessons/go/stage-4/level-2/lesson.md +++ b/lessons/go/stage-4/level-2/lesson.md @@ -51,14 +51,14 @@ Build a complete Text Analysis Tool application that: ### How to Run 1. **Run the code**: - ```bash + ``` go run hello.go - ```go + ``` **Expected output:** -```go +``` Hello, World! -```go +``` ### How to Approach This @@ -158,13 +158,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```go +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```go +``` Build incrementally - get one feature working before adding the next. @@ -207,46 +207,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```go -package main - -import "fmt" - -func main() { - fmt.Println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard go conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/go/stage-4/level-3/lesson.md b/lessons/go/stage-4/level-3/lesson.md index 2b5dff8..84812ee 100644 --- a/lessons/go/stage-4/level-3/lesson.md +++ b/lessons/go/stage-4/level-3/lesson.md @@ -51,14 +51,14 @@ Build a complete Data Processing application that: ### How to Run 1. **Run the code**: - ```bash + ``` go run hello.go - ```go + ``` **Expected output:** -```go +``` Hello, World! -```go +``` ### How to Approach This @@ -158,13 +158,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```go +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```go +``` Build incrementally - get one feature working before adding the next. @@ -207,46 +207,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```go -package main - -import "fmt" - -func main() { - fmt.Println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard go conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/go/stage-4/level-4/lesson.md b/lessons/go/stage-4/level-4/lesson.md index 56a6894..17e9a92 100644 --- a/lessons/go/stage-4/level-4/lesson.md +++ b/lessons/go/stage-4/level-4/lesson.md @@ -51,14 +51,14 @@ Build a complete File Operations application that: ### How to Run 1. **Run the code**: - ```bash + ``` go run hello.go - ```go + ``` **Expected output:** -```go +``` Hello, World! -```go +``` ### How to Approach This @@ -158,13 +158,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```go +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```go +``` Build incrementally - get one feature working before adding the next. @@ -207,46 +207,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```go -package main - -import "fmt" - -func main() { - fmt.Println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard go conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/go/stage-4/level-5/lesson.md b/lessons/go/stage-4/level-5/lesson.md index cc19644..2082b37 100644 --- a/lessons/go/stage-4/level-5/lesson.md +++ b/lessons/go/stage-4/level-5/lesson.md @@ -51,14 +51,14 @@ Build a complete API Integration application that: ### How to Run 1. **Run the code**: - ```bash + ``` go run hello.go - ```go + ``` **Expected output:** -```go +``` Hello, World! -```go +``` ### How to Approach This @@ -158,13 +158,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```go +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```go +``` Build incrementally - get one feature working before adding the next. @@ -207,46 +207,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```go -package main - -import "fmt" - -func main() { - fmt.Println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard go conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/go/stage-4/level-6/lesson.md b/lessons/go/stage-4/level-6/lesson.md index dc02a6e..25964e9 100644 --- a/lessons/go/stage-4/level-6/lesson.md +++ b/lessons/go/stage-4/level-6/lesson.md @@ -51,14 +51,14 @@ Build a complete Database Operations application that: ### How to Run 1. **Run the code**: - ```bash + ``` go run hello.go - ```go + ``` **Expected output:** -```go +``` Hello, World! -```go +``` ### How to Approach This @@ -158,13 +158,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```go +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```go +``` Build incrementally - get one feature working before adding the next. @@ -207,46 +207,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```go -package main - -import "fmt" - -func main() { - fmt.Println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard go conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/go/stage-4/level-7/lesson.md b/lessons/go/stage-4/level-7/lesson.md index b3f415a..2045ab6 100644 --- a/lessons/go/stage-4/level-7/lesson.md +++ b/lessons/go/stage-4/level-7/lesson.md @@ -51,14 +51,14 @@ Build a complete Complete Application application that: ### How to Run 1. **Run the code**: - ```bash + ``` go run hello.go - ```go + ``` **Expected output:** -```go +``` Hello, World! -```go +``` ### How to Approach This @@ -158,13 +158,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```go +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```go +``` Build incrementally - get one feature working before adding the next. @@ -207,46 +207,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```go -package main - -import "fmt" - -func main() { - fmt.Println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard go conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/go/stage-5/level-1/lesson.md b/lessons/go/stage-5/level-1/lesson.md index 82f7d52..4141db4 100644 --- a/lessons/go/stage-5/level-1/lesson.md +++ b/lessons/go/stage-5/level-1/lesson.md @@ -58,14 +58,14 @@ Create a production-ready Web Scraper using Go with: ### How to Run 1. **Run the code**: - ```bash + ``` go run hello.go - ```go + ``` **Expected output:** -```go +``` Hello, World! -```go +``` ### How to Approach This @@ -222,46 +222,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```go -package main - -import "fmt" - -func main() { - fmt.Println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard go conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/go/stage-5/level-2/lesson.md b/lessons/go/stage-5/level-2/lesson.md index 1750834..b94146c 100644 --- a/lessons/go/stage-5/level-2/lesson.md +++ b/lessons/go/stage-5/level-2/lesson.md @@ -58,14 +58,14 @@ Create a production-ready CLI Tool using Go with: ### How to Run 1. **Run the code**: - ```bash + ``` go run hello.go - ```go + ``` **Expected output:** -```go +``` Hello, World! -```go +``` ### How to Approach This @@ -222,46 +222,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```go -package main - -import "fmt" - -func main() { - fmt.Println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard go conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/go/stage-5/level-3/lesson.md b/lessons/go/stage-5/level-3/lesson.md index cc284b7..d07ea9f 100644 --- a/lessons/go/stage-5/level-3/lesson.md +++ b/lessons/go/stage-5/level-3/lesson.md @@ -58,14 +58,14 @@ Create a production-ready REST API using Go with: ### How to Run 1. **Run the code**: - ```bash + ``` go run hello.go - ```go + ``` **Expected output:** -```go +``` Hello, World! -```go +``` ### How to Approach This @@ -222,46 +222,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```go -package main - -import "fmt" - -func main() { - fmt.Println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard go conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/go/stage-5/level-4/lesson.md b/lessons/go/stage-5/level-4/lesson.md index af31e8c..cd045a0 100644 --- a/lessons/go/stage-5/level-4/lesson.md +++ b/lessons/go/stage-5/level-4/lesson.md @@ -58,14 +58,14 @@ Create a production-ready Data Visualization using Go with: ### How to Run 1. **Run the code**: - ```bash + ``` go run hello.go - ```go + ``` **Expected output:** -```go +``` Hello, World! -```go +``` ### How to Approach This @@ -222,46 +222,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```go -package main - -import "fmt" - -func main() { - fmt.Println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard go conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/go/stage-5/level-5/lesson.md b/lessons/go/stage-5/level-5/lesson.md index 1d4e43f..6405f96 100644 --- a/lessons/go/stage-5/level-5/lesson.md +++ b/lessons/go/stage-5/level-5/lesson.md @@ -58,14 +58,14 @@ Create a production-ready Automated Testing using Go with: ### How to Run 1. **Run the code**: - ```bash + ``` go run hello.go - ```go + ``` **Expected output:** -```go +``` Hello, World! -```go +``` ### How to Approach This @@ -222,46 +222,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```go -package main - -import "fmt" - -func main() { - fmt.Println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard go conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/go/stage-5/level-6/lesson.md b/lessons/go/stage-5/level-6/lesson.md index 30b6e5f..60e1220 100644 --- a/lessons/go/stage-5/level-6/lesson.md +++ b/lessons/go/stage-5/level-6/lesson.md @@ -58,14 +58,14 @@ Create a production-ready Performance Optimization using Go with: ### How to Run 1. **Run the code**: - ```bash + ``` go run hello.go - ```go + ``` **Expected output:** -```go +``` Hello, World! -```go +``` ### How to Approach This @@ -222,46 +222,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```go -package main - -import "fmt" - -func main() { - fmt.Println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard go conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/go/stage-5/level-7/lesson.md b/lessons/go/stage-5/level-7/lesson.md index 3b3d7b5..50a1f09 100644 --- a/lessons/go/stage-5/level-7/lesson.md +++ b/lessons/go/stage-5/level-7/lesson.md @@ -58,14 +58,14 @@ Create a production-ready Final Capstone Project using Go with: ### How to Run 1. **Run the code**: - ```bash + ``` go run hello.go - ```go + ``` **Expected output:** -```go +``` Hello, World! -```go +``` ### How to Approach This @@ -222,46 +222,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```go -package main - -import "fmt" - -func main() { - fmt.Println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard go conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/java/stage-1/level-1/lesson.md b/lessons/java/stage-1/level-1/lesson.md index 9fbbec0..c7f0c51 100644 --- a/lessons/java/stage-1/level-1/lesson.md +++ b/lessons/java/stage-1/level-1/lesson.md @@ -23,33 +23,33 @@ Welcome to your first step into programming with Java! Today, you'll learn how t **Copy the following code EXACTLY as shown below into `main.java`** -```java +``` public class Main { public static void main(String[] args) { System.out.println("Hello, World!"); } } -```java +``` --- ### How to Run **Method 1 (Vim - Recommended):** -```java +``` r -```java +``` **Method 2 (Terminal):** -```bash +``` javac main.java java Main -```java +``` **Expected output:** -```java +``` Hello, World! -```java +``` --- @@ -98,13 +98,13 @@ Remember to check the `VIM_CHEATSHEET.md` in the root directory for basic Vim co ### Code Breakdown -```java +``` public class Main { public static void main(String[] args) { System.out.println("Hello, World!"); } } -```java +``` - **`public class Main`** = Class declaration (public = accessible everywhere) - **`main`** = Special method where Java starts execution diff --git a/lessons/java/stage-1/level-2/lesson.md b/lessons/java/stage-1/level-2/lesson.md index b1afc15..25ccb9c 100644 --- a/lessons/java/stage-1/level-2/lesson.md +++ b/lessons/java/stage-1/level-2/lesson.md @@ -23,7 +23,7 @@ Now that you can run Java code, let's learn about **variables** - containers tha **Copy the following code EXACTLY into `main.java`** -```java +``` public class Main { public static void main(String[] args) { String name = "Alice"; @@ -35,7 +35,7 @@ public class Main { System.out.println("Height: " + height); } } -```java +``` --- @@ -44,17 +44,17 @@ public class Main { **Vim:** `r` **Terminal:** -```bash +``` javac main.java java Main -```java +``` **Expected output:** -```java +``` Name: Alex Age: 25 Price: $29.99 -```java +``` --- @@ -77,9 +77,9 @@ You just used **three different data types** in Java: - **`double`** - Decimal numbers (with decimal point) Each line follows this pattern: -```java +``` [type] [variableName] = [value]; -```java +``` When you use `+` between strings and variables, Java converts them to text and joins them together! @@ -101,11 +101,11 @@ When you use `+` between strings and variables, Java converts them to text and j ### Code Breakdown -```java +``` String name = "Alice"; // Text variable int age = 25; // Whole number variable double height = 5.7; // Decimal number variable -```java +``` Each variable has: - **Type**: What kind of data (String, int, double) @@ -114,9 +114,9 @@ Each variable has: ### String Concatenation -```java +``` System.out.println("Name: " + name); -```java +``` The `+` operator concatenates (joins) strings and converts variables to text! diff --git a/lessons/java/stage-1/level-3/lesson.md b/lessons/java/stage-1/level-3/lesson.md index e6b9e1b..476fa9b 100644 --- a/lessons/java/stage-1/level-3/lesson.md +++ b/lessons/java/stage-1/level-3/lesson.md @@ -23,7 +23,7 @@ Learn how to perform **mathematical operations** in Java. Math is everywhere in **Copy the following code EXACTLY into `main.java`** -```java +``` public class Main { public static void main(String[] args) { int x = 10; @@ -36,7 +36,7 @@ public class Main { System.out.println("Modulo (remainder): " + (x % y)); } } -```java +``` --- @@ -45,19 +45,19 @@ public class Main { **Vim:** `r` **Terminal:** -```bash +``` javac main.java java Main -```java +``` **Expected output:** -```java +``` Addition: 13 Subtraction: 7 Multiplication: 30 Division: 3 Modulo (remainder): 1 -```java +``` --- @@ -100,11 +100,11 @@ The parentheses `(x + y)` ensure the calculation happens before printing! ### Code Breakdown -```java +``` int x = 10; int y = 3; System.out.println("Addition: " + (x + y)); // 10 + 3 = 13 -```java +``` The `(x + y)` happens first (operator precedence), then concatenates with the string. @@ -120,10 +120,10 @@ The `(x + y)` happens first (operator precedence), then concatenates with the st ### Integer vs Floating Point Division -```java +``` int a = 10 / 3; // Result: 3 (not 3.33) double b = 10.0 / 3; // Result: 3.333... -```java +``` Integer division truncates (cuts off) decimals! diff --git a/lessons/java/stage-1/level-4/lesson.md b/lessons/java/stage-1/level-4/lesson.md index 6a13620..4dfe4f8 100644 --- a/lessons/java/stage-1/level-4/lesson.md +++ b/lessons/java/stage-1/level-4/lesson.md @@ -24,7 +24,7 @@ Get ready to make your programs interactive! Today you'll learn how to talk to y **Copy the following code EXACTLY as shown below into `Main.java`** -```java +``` import java.util.Scanner; public class Main { @@ -114,34 +114,34 @@ public class Main { input.close(); } } -```java +``` --- **Expected output:** -```java +``` [Interactive - output varies based on user input] -```java +``` ### How to Run **Method 1 (Vim - Recommended):** -```java +``` r -```java +``` **Method 2 (Terminal):** -```bash +``` javac Main.java java Main -```java +``` **Follow the prompts** and enter your information when asked! **Example interaction:** -```java +``` === Personal Information Form === What's your first name? Alex @@ -173,7 +173,7 @@ How many years into the future should we predict? 10 In 10 years, you'll be 35 years old! Thanks for using the personal info calculator, Alex! -```java +``` --- @@ -234,60 +234,60 @@ Always close your Scanner with `input.close()` when you're done! This is good pr ### Code Breakdown -```java +``` import java.util.Scanner; -```java +``` - **`import`** = Brings in external classes we need - **`java.util.Scanner`** = The Scanner class for reading input - **Why needed?** Scanner isn't built into Java core, must be imported -```java +``` Scanner input = new Scanner(System.in); -```java +``` - **`Scanner input`** = Declares a Scanner variable named "input" - **`new Scanner`** = Creates a new Scanner object - **`System.in`** = Standard input stream (keyboard) - **Think of it as**: Creating a tool that listens to the keyboard -```java +``` String name = input.nextLine(); -```java +``` - **`nextLine()`** = Reads entire line of text until Enter is pressed - **Best for**: Names, sentences, any text with spaces - **Returns**: String data type -```java +``` int age = input.nextInt(); -```java +``` - **`nextInt()`** = Reads the next integer number - **Warning**: Doesn't consume the newline character! - **Returns**: int data type -```java +``` input.nextLine(); // Clear the newline -```java +``` - **Why this line?** After `nextInt()` or `nextDouble()`, a newline character remains in the buffer - **Problem**: Next `nextLine()` would read that empty line - **Solution**: Call `nextLine()` once to consume it - **This is a common Java gotcha!** -```java +``` char grade = gradeStr.charAt(0); -```java +``` - **Why not direct char input?** Scanner has no `nextChar()` method - **Solution**: Read as String, extract first character - **`charAt(0)`** = Gets character at index 0 (first character) -```java +``` System.out.printf("Height in centimeters: %.1f cm\n", heightCm); -```java +``` - **`printf`** = Formatted print (like C's printf) - **`%.1f`** = Float with 1 decimal place - **`\n`** = Newline character -```java +``` input.close(); -```java +``` - **Purpose**: Closes the Scanner and releases resources - **Best practice**: Always close resources when done - **Prevents**: Resource leaks in larger applications @@ -297,18 +297,18 @@ input.close(); This is one of the most confusing issues for Java beginners: **The Problem:** -```java +``` int age = input.nextInt(); // User types: 25[Enter] // nextInt() reads "25" but leaves "[Enter]" in buffer! String name = input.nextLine(); // Reads that leftover Enter = empty string! -```java +``` **The Solution:** -```java +``` int age = input.nextInt(); input.nextLine(); // Consume the leftover newline String name = input.nextLine(); // Now this works correctly! -```java +``` **Rule of Thumb**: After using `nextInt()`, `nextDouble()`, or `nextFloat()`, always call `input.nextLine()` once to clear the buffer before reading more text. @@ -325,19 +325,19 @@ String name = input.nextLine(); // Now this works correctly! Scanner will crash if you enter the wrong type! Here's what happens: -```java +``` // If you enter "hello" when it expects int: int age = input.nextInt(); // Throws InputMismatchException! -```java +``` **Better approach (we'll learn this later):** -```java +``` if (input.hasNextInt()) { int age = input.nextInt(); } else { System.out.println("Please enter a valid number!"); } -```java +``` ### Common Errors & Solutions @@ -353,18 +353,18 @@ if (input.hasNextInt()) { We used two ways to combine strings and values: **Method 1: Using + operator** -```java +``` System.out.println("Name: " + name); System.out.println("Age: " + age + " years old"); -```java +``` - Simple and readable - Java automatically converts numbers to strings **Method 2: Using printf** -```java +``` System.out.printf("Height: %.1f cm\n", heightCm); System.out.printf("BMI: %.1f\n", bmi); -```java +``` - More control over formatting - Better for numbers with specific decimal places @@ -406,7 +406,7 @@ User input is everywhere: Create a simple restaurant order system: -```java +``` Scanner input = new Scanner(System.in); System.out.println("Welcome to Java Cafe!"); @@ -430,7 +430,7 @@ System.out.println("Sandwiches: " + sandwiches + " × $" + sandwichPrice); System.out.printf("Total: $%.2f\n", total); input.close(); -```java +``` --- diff --git a/lessons/java/stage-1/level-5/lesson.md b/lessons/java/stage-1/level-5/lesson.md index 02d205d..c63b6fa 100644 --- a/lessons/java/stage-1/level-5/lesson.md +++ b/lessons/java/stage-1/level-5/lesson.md @@ -24,7 +24,7 @@ Time to add intelligence to your programs! Today you'll learn how to make decisi **Copy the following code EXACTLY as shown below into `Main.java`** -```java +``` import java.util.Scanner; public class Main { @@ -150,34 +150,34 @@ public class Main { input.close(); } } -```java +``` --- **Expected output:** -```java +``` [Output depends on conditions - varies based on input] -```java +``` ### How to Run **Method 1 (Vim - Recommended):** -```java +``` r -```java +``` **Method 2 (Terminal):** -```bash +``` javac Main.java java Main -```java +``` **Follow all the prompts** and see how the program makes different decisions! **Example interaction:** -```java +``` === DECISION MAKER 3000 === Enter your age: 25 @@ -214,7 +214,7 @@ Weather Advice: === EVEN OR ODD === Enter a number: 42 42 is EVEN -```java +``` --- @@ -280,19 +280,19 @@ You learned the foundation of programming logic! Here's what's powerful: ### Code Breakdown -```java +``` if (age >= 18) { System.out.println("You are an adult!"); } else { System.out.println("You are a minor."); } -```java +``` - **`if`** = Tests a condition - **`age >= 18`** = Condition (must be true or false) - **`{}`** = Code block that runs if condition is true - **`else`** = Runs if condition is false -```java +``` if (score >= 90) { System.out.println("Grade: A"); } else if (score >= 80) { @@ -302,38 +302,38 @@ if (score >= 90) { } else { System.out.println("Grade: F"); } -```java +``` - **`else if`** = Tests another condition if previous was false - **Order matters!** Checks from top to bottom - **First match wins**: Once a condition is true, rest are skipped -```java +``` if (movieAge >= 17 || (movieAge >= 13 && hasConsent)) { System.out.println("You can watch R-rated movies!"); } -```java +``` - **`||`** = OR operator (either condition can be true) - **`&&`** = AND operator (both conditions must be true) - **`()`** = Parentheses control order of evaluation -```java +``` if (drivingAge >= 16) { if (hasPermit) { System.out.println("You can drive!"); } } -```java +``` - **Nested if** = An if statement inside another if statement - **Both conditions** must be true to reach inner code - **Useful for** complex decision trees -```java +``` String result = (number % 2 == 0) ? "EVEN" : "ODD"; -```java +``` - **Ternary operator** = Shorthand if-else for simple assignments - **Format**: `condition ? valueIfTrue : valueIfFalse` - **Same as**: - ```java + ``` String result; if (number % 2 == 0) { result = "EVEN"; @@ -345,26 +345,26 @@ String result = (number % 2 == 0) ? "EVEN" : "ODD"; ### Understanding Logical Operators **AND (&&) - Both must be true:** -```java +``` true && true = true true && false = false false && true = false false && false = false -```java +``` **OR (||) - At least one must be true:** -```java +``` true || true = true true || false = true false || true = true false || false = false -```java +``` **NOT (!) - Inverts the value:** -```java +``` !true = false !false = true -```java +``` ### Operator Precedence @@ -374,65 +374,65 @@ When combining conditions, Java evaluates in this order: 3. **`||`** (OR) - lowest priority **Example:** -```java +``` // Without parentheses: if (age > 18 || age == 18 && hasLicense) // Evaluates as: age > 18 || (age == 18 && hasLicense) // With parentheses (recommended for clarity): if ((age > 18 || age == 18) && hasLicense) -```java +``` ### Short-Circuit Evaluation Java is smart! It doesn't waste time: **AND (`&&`):** -```java +``` if (false && expensiveFunction()) { // expensiveFunction() is NEVER called! // Because false && anything = false } -```java +``` **OR (`||`):** -```java +``` if (true || expensiveFunction()) { // expensiveFunction() is NEVER called! // Because true || anything = true } -```java +``` **Practical use:** -```java +``` // Prevents division by zero: if (denominator != 0 && numerator / denominator > 10) { // Safe! Division only happens if denominator != 0 } -```java +``` ### Common Mistakes **1. Using `=` instead of `==`:** -```java +``` // WRONG: if (age = 18) { // Assignment, not comparison! // RIGHT: if (age == 18) { // Comparison -```java +``` **2. Comparing strings with `==`:** -```java +``` // WRONG: if (name == "John") { // Compares memory addresses! // RIGHT: if (name.equals("John")) { // Compares content -```java +``` **3. Missing braces in if statements:** -```java +``` // DANGEROUS: if (age < 18) System.out.println("Minor"); @@ -443,10 +443,10 @@ if (age < 18) { System.out.println("Minor"); System.out.println("Cannot vote"); } -```java +``` **4. Redundant conditions:** -```java +``` // REDUNDANT: if (age >= 18 && age < 65) { // ... @@ -460,7 +460,7 @@ if (age >= 18 && age < 65) { } else { // Automatically means age < 18 or age >= 65 // ... } -```java +``` ### Common Errors & Solutions @@ -474,7 +474,7 @@ if (age >= 18 && age < 65) { ### Advanced Patterns **1. Range checking:** -```java +``` if (score >= 90 && score <= 100) { System.out.println("A"); } @@ -483,18 +483,18 @@ if (score >= 90 && score <= 100) { if (90 <= score && score <= 100) { // Math notation System.out.println("A"); } -```java +``` **2. Flag variables:** -```java +``` boolean isEligible = (age >= 18 && hasID && !isBanned); if (isEligible) { System.out.println("Welcome!"); } -```java +``` **3. Guard clauses (early returns):** -```java +``` public static void processAge(int age) { if (age < 0) { System.out.println("Invalid age"); @@ -506,10 +506,10 @@ public static void processAge(int age) { } System.out.println("Adult"); } -```java +``` **4. Switch statement (alternative to many else-if):** -```java +``` int day = 3; switch (day) { case 1: @@ -524,7 +524,7 @@ switch (day) { default: System.out.println("Other day"); } -```java +``` ### Bonus Knowledge diff --git a/lessons/java/stage-1/level-6/lesson.md b/lessons/java/stage-1/level-6/lesson.md index ddae6b2..0ec53d6 100644 --- a/lessons/java/stage-1/level-6/lesson.md +++ b/lessons/java/stage-1/level-6/lesson.md @@ -24,7 +24,7 @@ Get ready for programming superpowers! Today you'll learn how to repeat actions **Copy the following code EXACTLY as shown below into `Main.java`** -```java +``` import java.util.Scanner; public class Main { @@ -181,29 +181,29 @@ public class Main { input.close(); } } -```java +``` --- **Expected output:** -```java +``` 1 2 3 4 5 6 7 8 9 10 -```java +``` ### How to Run **Method 1 (Vim - Recommended):** -```java +``` r -```java +``` **Method 2 (Terminal):** -```bash +``` javac Main.java java Main -```java +``` **Follow the prompts** and see loops in action! @@ -268,11 +268,11 @@ You learned the power of repetition! Here's what makes loops essential: ### Code Breakdown -```java +``` for (int i = 1; i <= 5; i++) { System.out.println("Count: " + i); } -```java +``` - **`for`** = Loop keyword - **`int i = 1`** = Initialization (runs once at start) - **`i <= 5`** = Condition (checked before each iteration) @@ -286,47 +286,47 @@ for (int i = 1; i <= 5; i++) { 4. Check: Is `i <= 5`? Yes → run body 5. Repeat until condition is false -```java +``` while (guess != secretNumber) { // Code here runs while condition is true } -```java +``` - **`while`** = Loop keyword - **`guess != secretNumber`** = Condition (checked before each iteration) - **No initialization or update** = You manage these yourself - **Use when** = You don't know how many iterations needed -```java +``` do { // Code here runs at least once } while (choice != 4); -```java +``` - **`do`** = Loop keyword - **Body runs first** = Before checking condition - **`while (choice != 4)`** = Condition checked after body - **Use when** = Need to run at least once (like menus) -```java +``` if (i % 7 == 0) { break; // Exit loop immediately } -```java +``` - **`break`** = Exits the innermost loop - **All remaining iterations** = Skipped - **Use when** = Found what you're looking for -```java +``` if (i % 3 == 0) { continue; // Skip rest of this iteration } -```java +``` - **`continue`** = Jumps to next iteration - **Remaining code in loop** = Skipped for this iteration - **Loop continues** = Not terminated, just this iteration skipped ### For Loop Anatomy -```java +``` for (int i = 0; i < 10; i++) { // ┬─────┬─ ┬──┬─ ┬──┬ // │ │ │ │ │ │ @@ -338,30 +338,30 @@ for (int i = 0; i < 10; i++) { // └───────────────────── Loop keyword System.out.println(i); } -```java +``` ### Loop Variations **Count up:** -```java +``` for (int i = 0; i < 10; i++) // 0,1,2,3,4,5,6,7,8,9 for (int i = 1; i <= 10; i++) // 1,2,3,4,5,6,7,8,9,10 -```java +``` **Count down:** -```java +``` for (int i = 10; i > 0; i--) // 10,9,8,7,6,5,4,3,2,1 for (int i = 10; i >= 1; i--) // 10,9,8,7,6,5,4,3,2,1 -```java +``` **Custom increment:** -```java +``` for (int i = 0; i < 20; i += 2) // 0,2,4,6,8,10,12,14,16,18 for (int i = 0; i < 50; i += 5) // 0,5,10,15,20,25,30,35,40,45 -```java +``` **Infinite loop:** -```java +``` for (;;) { // No initialization, condition, or update // Runs forever unless break is used } @@ -369,25 +369,25 @@ for (;;) { // No initialization, condition, or update while (true) { // Also runs forever } -```java +``` ### Nested Loops -```java +``` for (int row = 1; row <= 3; row++) { // Outer loop: rows for (int col = 1; col <= 4; col++) { // Inner loop: columns System.out.print("*"); } System.out.println(); // New line after each row } -```java +``` **Output:** -```java +``` **** **** **** -```java +``` **How it works:** - Outer loop runs 3 times (3 rows) @@ -397,36 +397,36 @@ for (int row = 1; row <= 3; row++) { // Outer loop: rows ### Common Loop Patterns **1. Sum/Average:** -```java +``` int sum = 0; for (int i = 1; i <= 10; i++) { sum += i; } double average = (double)sum / 10; -```java +``` **2. Find maximum:** -```java +``` int max = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] > max) { max = array[i]; } } -```java +``` **3. Count occurrences:** -```java +``` int count = 0; for (int i = 0; i < length; i++) { if (condition) { count++; } } -```java +``` **4. Search:** -```java +``` boolean found = false; for (int i = 0; i < array.length; i++) { if (array[i] == target) { @@ -434,7 +434,7 @@ for (int i = 0; i < array.length; i++) { break; } } -```java +``` ### Common Errors & Solutions @@ -452,7 +452,7 @@ for (int i = 0; i < array.length; i++) { - **Use while**: When condition-based **Optimization tips:** -```java +``` // SLOW: Recalculates length every iteration for (int i = 0; i < array.length; i++) { } @@ -462,11 +462,11 @@ for (int i = 0; i < len; i++) { } // FASTEST: Enhanced for loop (Java 5+) for (int value : array) { } -```java +``` ### Enhanced For Loop (For-Each) -```java +``` int[] numbers = {1, 2, 3, 4, 5}; // Traditional for loop: @@ -478,7 +478,7 @@ for (int i = 0; i < numbers.length; i++) { for (int number : numbers) { System.out.println(number); } -```java +``` **Advantages:** - Cleaner syntax diff --git a/lessons/java/stage-1/level-7/lesson.md b/lessons/java/stage-1/level-7/lesson.md index c65ad66..00bd261 100644 --- a/lessons/java/stage-1/level-7/lesson.md +++ b/lessons/java/stage-1/level-7/lesson.md @@ -23,18 +23,18 @@ Organize your code into reusable functions/methods. **Copy the following code EXACTLY as shown below into `main.java`** -```java +``` public class Main { // Function to greet someone public static void greet(String name) { System.out.println("Hello, " + name + "!"); } - + // Function that returns a value public static int add(int a, int b) { return a + b; } - + // Function to calculate factorial public static long factorial(int n) { long result = 1; @@ -43,38 +43,38 @@ public class Main { } return result; } - + public static void main(String[] args) { greet("Alice"); greet("Bob"); - + int sum = add(5, 3); System.out.println("5 + 3 = " + sum); - + System.out.println("5! = " + factorial(5)); } } -```java +``` --- ### How to Run **Method 1 (Vim - Recommended):** -```java +``` r -```java +``` **Method 2 (Terminal):** -```bash +``` javac Main.java java Main -```java +``` **Expected output:** -```java +``` Result: 15 -```java +``` --- @@ -122,45 +122,53 @@ You just created a real Java program! Here's what makes it work: --- -## ANSWER KEY (No peeking until you've tried!) +## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -The code you copied demonstrates fundamental Java concepts: +``` +public class Main { + // Function to greet someone + public static void greet(String name) { + System.out.println("Hello, " + name + "!"); + } -**Key Components:** -- Syntax rules specific to Java -- How data is stored and manipulated -- Input/output operations -- Program flow and structure + // Function that returns a value + public static int add(int a, int b) { + return a + b; + } -### Common Errors & Solutions + // Function to calculate factorial + public static long factorial(int n) { + long result = 1; + for (int i = 1; i <= n; i++) { + result *= i; + } + return result; + } + + public static void main(String[] args) { + greet("Alice"); + greet("Bob"); + + int sum = add(5, 3); + System.out.println("5 + 3 = " + sum); -| Error | Cause | Solution | -|-------|-------|----------| -| Syntax error | Typo in code | Double-check spelling and punctuation | -| Runtime error | Code runs but crashes | Check your logic and data types | -| Unexpected output | Logic error | Review your algorithm step-by-step | -| Compilation error | Code won't compile | Fix syntax before running | + System.out.println("5! = " + factorial(5)); + } +} +``` -### Bonus Knowledge +### Explanation -- Java has a rich ecosystem of libraries and tools -- Understanding these basics prepares you for advanced topics -- Practice is key - try writing similar programs from scratch -- Every expert programmer started exactly where you are now! +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -### Real-World Applications +### Success Criteria -This concept is used in: -1. Professional software development -2. Web applications and mobile apps -3. Data analysis and scientific computing -4. Automation and scripting -5. Game development +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -**Excellent work! You've mastered a fundamental concept!** - -*Ready for the next challenge? Keep going!* +**Great job! You've completed this lesson!** diff --git a/lessons/java/stage-2/level-1/lesson.md b/lessons/java/stage-2/level-1/lesson.md index 441fe6c..b718241 100644 --- a/lessons/java/stage-2/level-1/lesson.md +++ b/lessons/java/stage-2/level-1/lesson.md @@ -25,7 +25,7 @@ Welcome to Stage 2! You've mastered copying code - now it's time to think like a **Pseudocode** is a way to write programming logic in plain English (or your native language) before writing actual code. It's like writing a recipe or instructions for a task. **Example:** -```java +``` Algorithm: Make a sandwich 1. Get bread from pantry 2. Get peanut butter from fridge @@ -34,7 +34,7 @@ Algorithm: Make a sandwich 5. Spread jelly on the other bread slice 6. Put slices together 7. Enjoy your sandwich! -```java +``` This is much easier to understand than trying to write code first! @@ -50,30 +50,30 @@ This is much easier to understand than trying to write code first! ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` javac hello.java ``` 2. **Run your program**: - ```bash + ``` java hello ``` **Expected output:** -```java +``` Hello, World! -```java +``` ## Algorithm 1: Greeting Program **Pseudocode:** -```java +``` Algorithm: Display Personal Greeting 1. Display "Hello! What's your name?" to the user 2. Get the user's name from input 3. Display "Nice to meet you, " followed by the user's name 4. Display "Welcome to programming!" -```java +``` **Your Task:** Create a Java program that follows these exact steps. @@ -82,7 +82,7 @@ Algorithm: Display Personal Greeting ## Algorithm 2: Simple Calculator **Pseudocode:** -```java +``` Algorithm: Add Two Numbers 1. Ask user for first number 2. Get first number from user @@ -90,7 +90,7 @@ Algorithm: Add Two Numbers 4. Get second number from user 5. Calculate sum of the two numbers 6. Display "The sum is: " followed by the sum -```java +``` **Your Task:** Create a Java program that implements this calculator. @@ -99,14 +99,14 @@ Algorithm: Add Two Numbers ## Algorithm 3: Age Calculator **Pseudocode:** -```java +``` Algorithm: Calculate Age in Days 1. Display "Enter your age in years: " 2. Get age in years from user 3. Calculate days = age × 365 4. Display "You are approximately " + days + " days old" 5. Display "That's a lot of days!" -```java +``` **Your Task:** Create a program that calculates approximate age in days. @@ -115,7 +115,7 @@ Algorithm: Calculate Age in Days ## Algorithm 4: Temperature Converter **Pseudocode:** -```java +``` Algorithm: Celsius to Fahrenheit Converter 1. Display "Enter temperature in Celsius: " 2. Get temperature in Celsius from user @@ -124,7 +124,7 @@ Algorithm: Celsius to Fahrenheit Converter 5. Display "°C = " 6. Display the Fahrenheit temperature 7. Display "°F" -```java +``` **Your Task:** Create a temperature conversion program. @@ -133,7 +133,7 @@ Algorithm: Celsius to Fahrenheit Converter ## Algorithm 5: Rectangle Area Calculator **Pseudocode:** -```java +``` Algorithm: Calculate Rectangle Area 1. Display "Rectangle Area Calculator" 2. Display "Enter length: " @@ -144,7 +144,7 @@ Algorithm: Calculate Rectangle Area 7. Calculate perimeter = 2 × (length + width) 8. Display "Area: " + area 9. Display "Perimeter: " + perimeter -```java +``` **Your Task:** Create a program that calculates both area and perimeter. @@ -153,7 +153,7 @@ Algorithm: Calculate Rectangle Area ## Algorithm 6: Simple Interest Calculator **Pseudocode:** -```java +``` Algorithm: Calculate Simple Interest 1. Display "Simple Interest Calculator" 2. Display "Enter principal amount: $" @@ -167,7 +167,7 @@ Algorithm: Calculate Simple Interest 10. Display "Principal: $" + principal 11. Display "Interest: $" + interest 12. Display "Total: $" + total -```java +``` **Your Task:** Implement the complete interest calculation. @@ -232,7 +232,7 @@ Algorithm: Calculate Simple Interest ## Pseudocode Best Practices ### Good Pseudocode -```java +``` Algorithm: Process User Data 1. Get user's name 2. Get user's age @@ -241,18 +241,18 @@ Algorithm: Process User Data Else Display "Minor user" 4. Display "Data processed" -```java +``` ### Bad Pseudocode (Too Vague) -```java +``` Algorithm: Do stuff 1. Get things 2. Calculate something 3. Show results -```java +``` ### Good Pseudocode (Clear and Specific) -```java +``` Algorithm: Calculate BMI 1. Display "BMI Calculator" 2. Display "Enter weight in kg: " @@ -261,7 +261,7 @@ Algorithm: Calculate BMI 5. Get height from user 6. Calculate BMI = weight ÷ (height × height) 7. Display "Your BMI is: " + BMI -```java +``` --- @@ -273,23 +273,23 @@ Algorithm: Calculate BMI ### Algorithm 1: Greeting Program -```java +``` import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); - + System.out.print("Hello! What's your name? "); String name = input.nextLine(); - + System.out.println("Nice to meet you, " + name); System.out.println("Welcome to programming!"); - + input.close(); } } -```java +``` **Key Concepts:** - `Scanner input = new Scanner(System.in);` - Create Scanner for user input @@ -301,27 +301,27 @@ public class Main { ### Algorithm 2: Simple Calculator -```java +``` import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); - + System.out.print("Enter first number: "); int num1 = input.nextInt(); - + System.out.print("Enter second number: "); int num2 = input.nextInt(); - + int sum = num1 + num2; - + System.out.println("The sum is: " + sum); - + input.close(); } } -```java +``` **Key Concepts:** - `int num1 = input.nextInt();` - Read integer from user @@ -333,25 +333,25 @@ public class Main { ### Algorithm 3: Age Calculator -```java +``` import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); - + System.out.print("Enter your age in years: "); int ageYears = input.nextInt(); - + int ageDays = ageYears * 365; - + System.out.println("You are approximately " + ageDays + " days old"); System.out.println("That's a lot of days!"); - + input.close(); } } -```java +``` **Key Concepts:** - Simple multiplication: `ageDays = ageYears * 365;` @@ -362,24 +362,24 @@ public class Main { ### Algorithm 4: Temperature Converter -```java +``` import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); - + System.out.print("Enter temperature in Celsius: "); double celsius = input.nextDouble(); - + double fahrenheit = (celsius * 9.0/5.0) + 32; - + System.out.printf("%.1f°C = %.1f°F%n", celsius, fahrenheit); - + input.close(); } } -```java +``` **Key Concepts:** - `double` variables for decimal temperatures @@ -391,30 +391,30 @@ public class Main { ### Algorithm 5: Rectangle Area Calculator -```java +``` import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); - + System.out.println("Rectangle Area Calculator"); System.out.print("Enter length: "); double length = input.nextDouble(); - + System.out.print("Enter width: "); double width = input.nextDouble(); - + double area = length * width; double perimeter = 2 * (length + width); - + System.out.printf("Area: %.2f%n", area); System.out.printf("Perimeter: %.2f%n", perimeter); - + input.close(); } } -```java +``` **Key Concepts:** - Multiple calculations: area and perimeter @@ -425,34 +425,34 @@ public class Main { ### Algorithm 6: Simple Interest Calculator -```java +``` import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); - + System.out.println("Simple Interest Calculator"); System.out.print("Enter principal amount: $"); double principal = input.nextDouble(); - + System.out.print("Enter interest rate (%): "); double rate = input.nextDouble(); - + System.out.print("Enter time in years: "); double time = input.nextDouble(); - + double interest = (principal * rate * time) / 100; double total = principal + interest; - + System.out.printf("Principal: $%.2f%n", principal); System.out.printf("Interest: $%.2f%n", interest); System.out.printf("Total: $%.2f%n", total); - + input.close(); } } -```java +``` **Key Concepts:** - Complex formula: `(principal * rate * time) / 100` @@ -516,39 +516,39 @@ public class Main { ### Input/Output Patterns **Getting Integers:** -```java +``` Scanner input = new Scanner(System.in); System.out.print("Enter age: "); int age = input.nextInt(); -```java +``` **Getting Decimals:** -```java +``` System.out.print("Enter price: $"); double price = input.nextDouble(); -```java +``` **Getting Text:** -```java +``` System.out.print("Enter name: "); String name = input.nextLine(); -```java +``` **Displaying Results:** -```java +``` System.out.println("Result: " + result); System.out.printf("Price: $%.2f%n", price); System.out.println("Hello, " + name + "!"); -```java +``` **Important Scanner Note:** When mixing `nextInt()` or `nextDouble()` with `nextLine()`, you may need to add an extra `input.nextLine()` to clear the buffer: -```java +``` int age = input.nextInt(); input.nextLine(); // Clear the newline String name = input.nextLine(); // Now this works correctly -```java +``` --- diff --git a/lessons/java/stage-2/level-2/lesson.md b/lessons/java/stage-2/level-2/lesson.md index a5e0bae..95eec6a 100644 --- a/lessons/java/stage-2/level-2/lesson.md +++ b/lessons/java/stage-2/level-2/lesson.md @@ -43,24 +43,24 @@ Variables are the memory of your programs! Today you'll learn how to use variabl ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` javac hello.java ``` 2. **Run your program**: - ```bash + ``` java hello ``` **Expected output:** -```java +``` Hello, World! -```java +``` ## Algorithm 1: Shopping Cart Total **Pseudocode:** -```java +``` Algorithm: Calculate Shopping Total 1. Initialize total to 0 2. Initialize itemCount to 0 @@ -73,7 +73,7 @@ Algorithm: Calculate Shopping Total d. Get next price from user 6. Display "Items purchased: " + itemCount 7. Display "Total cost: $" + total -```java +``` **Variable Analysis:** - `total`: Accumulator (starts at 0, adds prices) @@ -87,7 +87,7 @@ Algorithm: Calculate Shopping Total ## Algorithm 2: Password Validation **Pseudocode:** -```java +``` Algorithm: Validate Password 1. Initialize attempts to 0 2. Initialize isValid to false @@ -102,7 +102,7 @@ Algorithm: Validate Password a. Display "Access granted! " 6. Else: a. Display "Access denied! " -```java +``` **Variable Analysis:** - `attempts`: Counter (tracks login attempts) @@ -117,7 +117,7 @@ Algorithm: Validate Password ## Algorithm 3: Grade Average Calculator **Pseudocode:** -```java +``` Algorithm: Calculate Class Average 1. Initialize totalScore to 0 2. Initialize studentCount to 0 @@ -136,7 +136,7 @@ Algorithm: Calculate Class Average c. Display "Total students: " + studentCount 6. Else: a. Display "No students entered" -```java +``` **Variable Analysis:** - `totalScore`: Accumulator (sums all grades) @@ -152,7 +152,7 @@ Algorithm: Calculate Class Average ## Algorithm 4: Number Guessing Game **Pseudocode:** -```java +``` Algorithm: Number Guessing Game 1. Initialize secretNumber to 42 2. Initialize guessCount to 0 @@ -171,7 +171,7 @@ Algorithm: Number Guessing Game ii. Else: i. Display "Too low! Try higher." 6. Display "Thanks for playing!" -```java +``` **Variable Analysis:** - `secretNumber`: Constant (game target) @@ -186,7 +186,7 @@ Algorithm: Number Guessing Game ## Algorithm 5: Bank Account Simulator **Pseudocode:** -```java +``` Algorithm: Bank Account Manager 1. Initialize balance to 1000.00 2. Initialize transactionCount to 0 @@ -219,7 +219,7 @@ Algorithm: Bank Account Manager g. Else: i. Display "Invalid choice!" 7. Display "Thank you for banking with us!" -```java +``` **Variable Analysis:** - `balance`: Accumulator (changes with deposits/withdrawals) @@ -235,7 +235,7 @@ Algorithm: Bank Account Manager ## Algorithm 6: Temperature Tracker **Pseudocode:** -```java +``` Algorithm: Daily Temperature Tracker 1. Initialize dayCount to 0 2. Initialize totalTemperature to 0 @@ -258,7 +258,7 @@ Algorithm: Daily Temperature Tracker 11. Display "Highest: " + highestTemp + "°F" 12. Display "Lowest: " + lowestTemp + "°F" 13. Display "Readings taken: " + readingCount -```java +``` **Variable Analysis:** - `totalTemperature`: Accumulator (sum of all readings) @@ -276,7 +276,7 @@ Algorithm: Daily Temperature Tracker **For each algorithm, track how variables change:** **Example for Algorithm 1:** -```java +``` Initial state: total = 0, itemCount = 0 @@ -291,7 +291,7 @@ total = 15.75, itemCount = 2 User enters: 0 (finish) Final state: total = 15.75, itemCount = 2 -```java +``` --- @@ -324,25 +324,25 @@ total = 15.75, itemCount = 2 ## Variable Patterns in Pseudocode ### Counter Variables -```java +``` Initialize counter to 0 While condition: Add 1 to counter // do something Display "Count: " + counter -```java +``` ### Accumulator Variables -```java +``` Initialize total to 0 While getting values: Get value from user Add value to total Display "Total: " + total -```java +``` ### Flag Variables -```java +``` Initialize isValid to false // check conditions If condition met: @@ -351,16 +351,16 @@ If isValid: Display "Success" Else: Display "Failed" -```java +``` ### Tracker Variables -```java +``` Initialize maximum to smallest possible value Initialize minimum to largest possible value For each value: If value > maximum: set maximum to value If value < minimum: set minimum to value -```java +``` --- @@ -372,34 +372,34 @@ For each value: ### Algorithm 1: Shopping Cart Total -```java +``` import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); - + double total = 0.0; int itemCount = 0; - + System.out.print("Enter price of item 1 (or 0 to finish): "); double price = scanner.nextDouble(); - + while (price != 0) { total = total + price; itemCount = itemCount + 1; - + System.out.print("Enter price of item " + (itemCount + 1) + " (or 0 to finish): "); price = scanner.nextDouble(); } - + System.out.println("Items purchased: " + itemCount); System.out.printf("Total cost: $%.2f\n", total); - + scanner.close(); } } -```java +``` **Variable Flow:** - `total`: Starts at 0, accumulates prices @@ -415,38 +415,38 @@ public class Main { ### Algorithm 2: Password Validation -```java +``` import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); - + int attempts = 0; boolean isValid = false; String correctPassword = "secret123"; - + while (attempts < 3 && !isValid) { attempts = attempts + 1; - + System.out.print("Enter password (attempt " + attempts + "/3): "); String userInput = scanner.nextLine(); - + if (userInput.equals(correctPassword)) { isValid = true; } } - + if (isValid) { System.out.println("Access granted! "); } else { System.out.println("Access denied! "); } - + scanner.close(); } } -```java +``` **Key Concepts:** - String comparison with `.equals()` (NOT ==!) @@ -461,21 +461,21 @@ public class Main { ### Algorithm 3: Grade Average Calculator -```java +``` import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); - + double totalScore = 0.0; int studentCount = 0; boolean hasMoreStudents = true; - + while (hasMoreStudents) { System.out.print("Enter score for student " + (studentCount + 1) + " (or -1 to finish): "); double score = scanner.nextDouble(); - + if (score == -1) { hasMoreStudents = false; } else { @@ -483,7 +483,7 @@ public class Main { studentCount = studentCount + 1; } } - + if (studentCount > 0) { double average = totalScore / studentCount; System.out.printf("Class average: %.1f%%\n", average); @@ -491,11 +491,11 @@ public class Main { } else { System.out.println("No students entered"); } - + scanner.close(); } } -```java +``` **Variable Management:** - `totalScore`: Accumulates all grades @@ -510,25 +510,25 @@ public class Main { ### Algorithm 4: Number Guessing Game -```java +``` import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); - + int secretNumber = 42; int guessCount = 0; boolean gameWon = false; - + System.out.println("I'm thinking of a number between 1-100!"); - + while (!gameWon) { guessCount = guessCount + 1; - + System.out.print("Guess #" + guessCount + ": "); int userGuess = scanner.nextInt(); - + if (userGuess == secretNumber) { gameWon = true; System.out.println("Correct! You won in " + guessCount + " guesses! "); @@ -540,13 +540,13 @@ public class Main { } } } - + System.out.println("Thanks for playing!"); - + scanner.close(); } } -```java +``` **Game Logic:** - `gameWon` flag controls the game loop @@ -562,20 +562,20 @@ public class Main { ### Algorithm 5: Bank Account Simulator -```java +``` import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); - + double balance = 1000.00; int transactionCount = 0; boolean isRunning = true; - + System.out.println("Welcome to Bank Account Manager"); System.out.printf("Initial balance: $%.2f\n", balance); - + while (isRunning) { System.out.println("\n1. Deposit"); System.out.println("2. Withdraw"); @@ -583,7 +583,7 @@ public class Main { System.out.println("4. Exit"); System.out.print("Enter choice: "); int userChoice = scanner.nextInt(); - + if (userChoice == 1) { System.out.print("Enter deposit amount: $"); double amount = scanner.nextDouble(); @@ -609,13 +609,13 @@ public class Main { System.out.println("Invalid choice!"); } } - + System.out.println("Thank you for banking with us!"); - + scanner.close(); } } -```java +``` **Complex Variable Management:** - `balance`: Changes with deposits/withdrawals @@ -631,50 +631,50 @@ public class Main { ### Algorithm 6: Temperature Tracker -```java +``` import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); - + int dayCount = 0; // Not used in this version, but could be for multiple days double totalTemperature = 0.0; double highestTemp = -1000.0; double lowestTemp = 1000.0; int readingCount = 0; - + System.out.println("Daily Temperature Tracker"); - + while (readingCount < 24) { readingCount = readingCount + 1; - + System.out.print("Enter temperature reading #" + readingCount + " (°F): "); double temperature = scanner.nextDouble(); - + totalTemperature = totalTemperature + temperature; - + if (temperature > highestTemp) { highestTemp = temperature; } - + if (temperature < lowestTemp) { lowestTemp = temperature; } } - + double averageTemp = totalTemperature / 24; - + System.out.println("\nTemperature Summary:"); System.out.printf("Average: %.1f°F\n", averageTemp); System.out.printf("Highest: %.1f°F\n", highestTemp); System.out.printf("Lowest: %.1f°F\n", lowestTemp); System.out.println("Readings taken: " + readingCount); - + scanner.close(); } } -```java +``` **Statistical Tracking:** - `highestTemp`: Tracks maximum value (initialized to very low) @@ -691,81 +691,81 @@ public class Main { ### Variable Initialization Best Practices **Counters:** Always start at 0 -```java +``` int count = 0; -```java +``` **Accumulators:** Usually start at 0 -```java +``` double total = 0.0; -```java +``` **Flags:** Initialize to false -```java +``` boolean isDone = false; -```java +``` **Maximum Trackers:** Initialize to minimum possible value -```java +``` double maxValue = Double.MIN_VALUE; // or a very small number like -1000 -```java +``` **Minimum Trackers:** Initialize to maximum possible value -```java +``` double minValue = Double.MAX_VALUE; // or a very large number like 1000 -```java +``` ### Common Variable Mistakes in Java **Forgetting Initialization:** -```java +``` int sum; // Uninitialized - compiler error in Java! sum = sum + 5; // Won't compile -```java +``` **Wrong Data Types:** -```java +``` int average; // Wrong! Should be double for decimals average = 85.5; // Compiler error - can't assign double to int -```java +``` **Scope Issues:** -```java +``` if (condition) { int temp = 5; // Only exists in this block } // temp is undefined here - compiler error! -```java +``` **String Comparison:** -```java +``` String password = "secret"; if (password == "secret") { } // WRONG! Compares references if (password.equals("secret")) { } // CORRECT! Compares content -```java +``` --- ### Java Variable Naming Conventions **camelCase for variables:** -```java +``` int studentCount = 0; // Good int student_count = 0; // Not Java style (that's C/Python) int StudentCount = 0; // That's for class names -```java +``` **Descriptive names:** -```java +``` double total = 0.0; // Clear purpose double t = 0.0; // Too short, unclear double totalPriceInDollars; // Very clear -```java +``` **Constants (final):** -```java +``` final int MAX_ATTEMPTS = 3; // UPPERCASE for constants -```java +``` --- diff --git a/lessons/java/stage-2/level-3/lesson.md b/lessons/java/stage-2/level-3/lesson.md index f0b760f..e695fc8 100644 --- a/lessons/java/stage-2/level-3/lesson.md +++ b/lessons/java/stage-2/level-3/lesson.md @@ -43,24 +43,24 @@ Mathematics is the language of algorithms! Today you'll translate mathematical c ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` javac hello.java ``` 2. **Run your program**: - ```bash + ``` java hello ``` **Expected output:** -```java +``` Hello, World! -```java +``` ## Algorithm 1: Geometry Calculator **Pseudocode:** -```java +``` Algorithm: Calculate Circle Properties 1. Display "Circle Calculator" 2. Display "Enter radius: " @@ -72,7 +72,7 @@ Algorithm: Calculate Circle Properties 8. Display "Diameter: " + diameter 9. Display "Area: " + area 10. Display "Circumference: " + circumference -```java +``` **Mathematical Notes:** - π (pi) ≈ 3.14159 (or use `Math.PI`) @@ -86,7 +86,7 @@ Algorithm: Calculate Circle Properties ## Algorithm 2: Right Triangle Solver **Pseudocode:** -```java +``` Algorithm: Solve Right Triangle 1. Display "Right Triangle Calculator" 2. Display "Enter side A: " @@ -101,7 +101,7 @@ Algorithm: Solve Right Triangle 11. Display "Hypotenuse: " + hypotenuse 12. Display "Area: " + area 13. Display "Perimeter: " + perimeter -```java +``` **Mathematical Notes:** - Pythagorean theorem: c² = a² + b² (where c is hypotenuse) @@ -115,7 +115,7 @@ Algorithm: Solve Right Triangle ## Algorithm 3: Compound Interest Calculator **Pseudocode:** -```java +``` Algorithm: Calculate Compound Interest 1. Display "Compound Interest Calculator" 2. Display "Enter principal amount: $" @@ -134,7 +134,7 @@ Algorithm: Calculate Compound Interest 15. Display "Principal: $" + principal 16. Display "Final Amount: $" + finalAmount 17. Display "Total Interest: $" + totalInterest -```java +``` **Mathematical Notes:** - Compound interest formula: A = P(1 + r/n)^(nt) @@ -148,7 +148,7 @@ Algorithm: Calculate Compound Interest ## Algorithm 4: Quadratic Equation Solver **Pseudocode:** -```java +``` Algorithm: Solve Quadratic Equation 1. Display "Quadratic Equation Solver" 2. Display "For equation ax² + bx + c = 0" @@ -169,7 +169,7 @@ Algorithm: Solve Quadratic Equation 12. Else: a. Display "No real roots (complex solutions)" 13. Display "Discriminant: " + discriminant -```java +``` **Mathematical Notes:** - Quadratic formula: x = [-b ± √(b² - 4ac)] / 2a @@ -183,7 +183,7 @@ Algorithm: Solve Quadratic Equation ## Algorithm 5: Fibonacci Sequence Generator **Pseudocode:** -```java +``` Algorithm: Generate Fibonacci Sequence 1. Display "Fibonacci Sequence Generator" 2. Display "Enter number of terms: " @@ -203,7 +203,7 @@ Algorithm: Generate Fibonacci Sequence d. Set second = next e. Add 1 to count 11. Display "Sequence complete" -```java +``` **Mathematical Notes:** - Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, ... @@ -217,7 +217,7 @@ Algorithm: Generate Fibonacci Sequence ## Algorithm 6: Statistical Calculator **Pseudocode:** -```java +``` Algorithm: Calculate Statistics 1. Display "Statistical Calculator" 2. Initialize sum = 0 @@ -243,7 +243,7 @@ Algorithm: Calculate Statistics g. Display "Standard Deviation: " + standardDeviation 8. Else: a. Display "No numbers entered" -```java +``` **Mathematical Notes:** - Mean (average): μ = Σx / n @@ -257,7 +257,7 @@ Algorithm: Calculate Statistics ## Algorithm 7: Distance Calculator (Coordinate Geometry) **Pseudocode:** -```java +``` Algorithm: Calculate Distance Between Points 1. Display "Distance Between Two Points" 2. Display "Enter coordinates for point 1:" @@ -276,7 +276,7 @@ Algorithm: Calculate Distance Between Points 15. Display "Point 1: (" + x1 + ", " + y1 + ")" 16. Display "Point 2: (" + x2 + ", " + y2 + ")" 17. Display "Distance: " + distance -```java +``` **Mathematical Notes:** - Distance formula: d = √[(x₂ - x₁)² + (y₂ - y₁)²] @@ -359,30 +359,30 @@ Algorithm: Calculate Distance Between Points ### Algorithm 1: Geometry Calculator -```java +``` import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); - + System.out.println("Circle Calculator"); System.out.print("Enter radius: "); double radius = scanner.nextDouble(); - + double area = Math.PI * radius * radius; double circumference = 2 * Math.PI * radius; double diameter = 2 * radius; - + System.out.printf("Radius: %.2f\n", radius); System.out.printf("Diameter: %.2f\n", diameter); System.out.printf("Area: %.2f\n", area); System.out.printf("Circumference: %.2f\n", circumference); - + scanner.close(); } } -```java +``` **Key Concepts:** - `Math.PI` constant for π @@ -397,33 +397,33 @@ public class Main { ### Algorithm 2: Right Triangle Solver -```java +``` import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); - + System.out.println("Right Triangle Calculator"); System.out.print("Enter side A: "); double sideA = scanner.nextDouble(); System.out.print("Enter side B: "); double sideB = scanner.nextDouble(); - + double hypotenuse = Math.sqrt(sideA * sideA + sideB * sideB); double area = (sideA * sideB) / 2; double perimeter = sideA + sideB + hypotenuse; - + System.out.printf("Side A: %.2f\n", sideA); System.out.printf("Side B: %.2f\n", sideB); System.out.printf("Hypotenuse: %.2f\n", hypotenuse); System.out.printf("Area: %.2f\n", area); System.out.printf("Perimeter: %.2f\n", perimeter); - + scanner.close(); } } -```java +``` **Key Concepts:** - `Math.sqrt()` for square root function @@ -438,13 +438,13 @@ public class Main { ### Algorithm 3: Compound Interest Calculator -```java +``` import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); - + System.out.println("Compound Interest Calculator"); System.out.print("Enter principal amount: $"); double principal = scanner.nextDouble(); @@ -454,22 +454,22 @@ public class Main { double years = scanner.nextDouble(); System.out.print("Enter compounding frequency (1=annual, 12=monthly): "); double frequency = scanner.nextDouble(); - + double rateDecimal = rate / 100; double totalCompounds = years * frequency; double compoundRate = rateDecimal / frequency; - + double finalAmount = principal * Math.pow(1 + compoundRate, totalCompounds); double totalInterest = finalAmount - principal; - + System.out.printf("Principal: $%.2f\n", principal); System.out.printf("Final Amount: $%.2f\n", finalAmount); System.out.printf("Total Interest: $%.2f\n", totalInterest); - + scanner.close(); } } -```java +``` **Key Concepts:** - Complex compound interest formula @@ -484,13 +484,13 @@ public class Main { ### Algorithm 4: Quadratic Equation Solver -```java +``` import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); - + System.out.println("Quadratic Equation Solver"); System.out.println("For equation ax² + bx + c = 0"); System.out.print("Enter coefficient a: "); @@ -499,11 +499,11 @@ public class Main { double b = scanner.nextDouble(); System.out.print("Enter coefficient c: "); double c = scanner.nextDouble(); - + double discriminant = b * b - 4 * a * c; - + System.out.printf("Discriminant: %.2f\n", discriminant); - + if (discriminant > 0) { double root1 = (-b + Math.sqrt(discriminant)) / (2 * a); double root2 = (-b - Math.sqrt(discriminant)) / (2 * a); @@ -514,11 +514,11 @@ public class Main { } else { System.out.println("No real roots (complex solutions)"); } - + scanner.close(); } } -```java +``` **Key Concepts:** - Discriminant determines number of roots @@ -533,43 +533,43 @@ public class Main { ### Algorithm 5: Fibonacci Sequence Generator -```java +``` import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); - + System.out.println("Fibonacci Sequence Generator"); System.out.print("Enter number of terms: "); int n = scanner.nextInt(); - + int first = 0, second = 1, count = 3; - + System.out.println("Fibonacci sequence:"); - + if (n >= 1) { System.out.print(first + " "); } if (n >= 2) { System.out.print(second + " "); } - + while (count <= n) { int next = first + second; System.out.print(next + " "); - + first = second; second = next; count++; } - + System.out.println("\nSequence complete"); - + scanner.close(); } } -```java +``` **Key Concepts:** - Iterative Fibonacci calculation @@ -585,23 +585,23 @@ public class Main { ### Algorithm 6: Statistical Calculator -```java +``` import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); - + double sum = 0, sumSquares = 0; int count = 0; boolean hasMore = true; - + System.out.println("Statistical Calculator"); - + while (hasMore) { System.out.print("Enter number " + (count + 1) + " (or 0 to finish): "); double number = scanner.nextDouble(); - + if (number == 0) { hasMore = false; } else { @@ -610,12 +610,12 @@ public class Main { sumSquares += number * number; } } - + if (count > 0) { double mean = sum / count; double variance = (sumSquares / count) - (mean * mean); double stdDev = Math.sqrt(variance); - + System.out.println("Count: " + count); System.out.printf("Sum: %.2f\n", sum); System.out.printf("Mean: %.2f\n", mean); @@ -623,11 +623,11 @@ public class Main { } else { System.out.println("No numbers entered"); } - + scanner.close(); } } -```java +``` **Key Concepts:** - Statistical formulas implementation @@ -643,39 +643,39 @@ public class Main { ### Algorithm 7: Distance Calculator -```java +``` import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); - + System.out.println("Distance Between Two Points"); - + System.out.println("Enter coordinates for point 1:"); System.out.print("X1: "); double x1 = scanner.nextDouble(); System.out.print("Y1: "); double y1 = scanner.nextDouble(); - + System.out.println("Enter coordinates for point 2:"); System.out.print("X2: "); double x2 = scanner.nextDouble(); System.out.print("Y2: "); double y2 = scanner.nextDouble(); - + double deltaX = x2 - x1; double deltaY = y2 - y1; double distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY); - + System.out.println("Point 1: (" + x1 + ", " + y1 + ")"); System.out.println("Point 2: (" + x2 + ", " + y2 + ")"); System.out.printf("Distance: %.2f\n", distance); - + scanner.close(); } } -```java +``` **Key Concepts:** - Distance formula in coordinate geometry @@ -693,29 +693,29 @@ public class Main { ### Common Math Mistakes in Java **Integer Division:** -```java +``` int result = 5 / 2; // Result: 2 (not 2.5!) -double result = 5.0 / 2; // Result: 2.5 -```java +double result = 5.0 / 2; // Result: 2.5 +``` **Parentheses Matter:** -```java +``` double wrong = 1 + 2 * 3; // 7 (multiplication first) double right = (1 + 2) * 3; // 9 (parentheses first) -```java +``` **Power vs Multiplication:** -```java +``` double wrong = x * 2; // This is x × 2, not x² double right = x * x; // This is x² double alsoRight = Math.pow(x, 2); // Also x² -```java +``` --- ### Math Class Quick Reference -```java +``` // Constants Math.PI // 3.14159265358979323846 Math.E // 2.71828182845904523536 @@ -739,7 +739,7 @@ Math.min(3, 7) // 3 (minimum) Math.sin(x) Math.cos(x) Math.tan(x) -```java +``` --- diff --git a/lessons/java/stage-2/level-4/lesson.md b/lessons/java/stage-2/level-4/lesson.md index 03c72a1..a82e4b1 100644 --- a/lessons/java/stage-2/level-4/lesson.md +++ b/lessons/java/stage-2/level-4/lesson.md @@ -32,24 +32,24 @@ User interaction is the heart of useful programs! Today you'll master the art of ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` javac hello.java ``` 2. **Run your program**: - ```bash + ``` java hello ``` **Expected output:** -```java +``` Hello, World! -```java +``` ## Algorithm 1: Age Verification System **Pseudocode:** -```java +``` Algorithm: Verify User Age 1. Display "=== Age Verification System ===" 2. Initialize isValidAge to false @@ -69,7 +69,7 @@ Algorithm: Verify User Age a. Display " You are an adult!" 6. Else: a. Display " You are a minor." -```java +``` **Input/Output Focus:** - Input validation (numeric, range checking) @@ -84,7 +84,7 @@ Algorithm: Verify User Age ## Algorithm 2: Restaurant Menu System **Pseudocode:** -```java +``` Algorithm: Restaurant Ordering System 1. Display "=== Welcome to Code Café ===" 2. Initialize totalCost to 0 @@ -121,7 +121,7 @@ Algorithm: Restaurant Ordering System 9. Display "Tax (8%): $" + tax 10. Display "Final total: $" + finalTotal 11. Display "Thank you for your order! " -```java +``` **Input/Output Focus:** - Clear menu formatting @@ -136,7 +136,7 @@ Algorithm: Restaurant Ordering System ## Algorithm 3: Student Grade Manager **Pseudocode:** -```java +``` Algorithm: Student Grade Management 1. Display "=== Student Grade Manager ===" 2. Initialize grades array (can hold 100 grades) @@ -195,7 +195,7 @@ Algorithm: Student Grade Management i. Else: i. Display " Invalid choice! Please select 1-5." 6. Display "Thank you for using Grade Manager! " -```java +``` **Input/Output Focus:** - Array data storage @@ -210,7 +210,7 @@ Algorithm: Student Grade Management ## Algorithm 4: Unit Converter **Pseudocode:** -```java +``` Algorithm: Unit Conversion Calculator 1. Display "=== Unit Converter ===" 2. Initialize isRunning to true @@ -266,7 +266,7 @@ Algorithm: Unit Conversion Calculator h. Else: i. Display " Invalid conversion type!" 4. Display "Thank you for using Unit Converter! " -```java +``` **Input/Output Focus:** - Nested menu systems @@ -281,7 +281,7 @@ Algorithm: Unit Conversion Calculator ## Algorithm 5: Survey Data Collector **Pseudocode:** -```java +``` Algorithm: Customer Satisfaction Survey 1. Display "=== Customer Satisfaction Survey ===" 2. Initialize responses array (can hold 50 responses) @@ -319,7 +319,7 @@ Algorithm: Customer Satisfaction Survey 7. Else: a. Display "No survey responses collected." 8. Display "Thank you for participating! " -```java +``` **Input/Output Focus:** - Clear survey instructions @@ -334,7 +334,7 @@ Algorithm: Customer Satisfaction Survey ## Algorithm 6: Library Book Tracker **Pseudocode:** -```java +``` Algorithm: Library Book Management 1. Display "=== Library Book Tracker ===" 2. Initialize books array (can hold 20 book titles) @@ -399,7 +399,7 @@ Algorithm: Library Book Management i. Else: i. Display " Invalid choice!" 6. Display "Thank you for using Library Book Tracker! " -```java +``` **Input/Output Focus:** - String array management @@ -414,27 +414,27 @@ Algorithm: Library Book Management ### Input Validation Techniques **Numeric Input Validation:** -```java +``` // Check if input is within range if (input >= minValue && input <= maxValue) { // Valid input } else { // Invalid input - show error } -```java +``` **String Input Validation:** -```java +``` // Check if string is not empty if (!inputString.isEmpty()) { // Valid input } else { // Empty input - show error } -```java +``` **Scanner Exception Handling:** -```java +``` Scanner scanner = new Scanner(System.in); try { @@ -444,7 +444,7 @@ try { scanner.nextLine(); // Clear invalid input System.out.println("Invalid input! Please enter a number."); } -```java +``` --- @@ -479,7 +479,7 @@ try { ## User Interface Design Principles ### Clear Menu Design -```java +``` === Main Menu === 1. Add Item - Add new item to collection 2. View Items - Display all items @@ -488,7 +488,7 @@ try { 5. Exit - Quit the program Enter choice (1-5): -```java +``` ### Error Message Best Practices - **Be specific**: "Grade must be between 0-100" not "Invalid input" @@ -512,7 +512,7 @@ Enter choice (1-5): ### Algorithm 1: Age Verification System -```java +``` import java.util.Scanner; import java.util.InputMismatchException; @@ -521,15 +521,15 @@ public class AgeVerification { Scanner scanner = new Scanner(System.in); int ageInput = 0; boolean isValidAge = false; - + System.out.println("=== Age Verification System ==="); - + while (!isValidAge) { System.out.print("Please enter your age (0-120): "); - + try { ageInput = scanner.nextInt(); - + if (ageInput < 0) { System.out.println(" Age cannot be negative!"); } else if (ageInput > 120) { @@ -542,19 +542,19 @@ public class AgeVerification { System.out.println(" Invalid input! Please enter a number."); } } - + System.out.println(" Age verified: " + ageInput + " years old"); - + if (ageInput >= 18) { System.out.println(" You are an adult!"); } else { System.out.println(" You are a minor."); } - + scanner.close(); } } -```java +``` **Key Concepts:** - Input validation with try-catch for InputMismatchException @@ -571,7 +571,7 @@ public class AgeVerification { ### Algorithm 2: Restaurant Menu System -```java +``` import java.util.Scanner; public class RestaurantMenu { @@ -580,9 +580,9 @@ public class RestaurantMenu { double totalCost = 0.0; boolean orderComplete = false; int choice; - + System.out.println("=== Welcome to Code Café ==="); - + while (!orderComplete) { System.out.println("\n1. Coffee - $3.50"); System.out.println("2. Sandwich - $8.75"); @@ -591,7 +591,7 @@ public class RestaurantMenu { System.out.println("5. Complete Order"); System.out.print("Enter your choice (1-5): "); choice = scanner.nextInt(); - + switch (choice) { case 1: totalCost += 3.50; @@ -617,21 +617,21 @@ public class RestaurantMenu { break; } } - + System.out.println("\n=== Order Summary ==="); System.out.printf("Total cost: $%.2f\n", totalCost); - + double tax = totalCost * 0.08; double finalTotal = totalCost + tax; - + System.out.printf("Tax (8%%): $%.2f\n", tax); System.out.printf("Final total: $%.2f\n", finalTotal); System.out.println("Thank you for your order! "); - + scanner.close(); } } -```java +``` **Key Concepts:** - Switch statement for menu handling @@ -654,7 +654,7 @@ public class RestaurantMenu { ### Algorithm 3: Student Grade Manager -```java +``` import java.util.Scanner; public class GradeManager { @@ -664,9 +664,9 @@ public class GradeManager { int gradeCount = 0; boolean isRunning = true; int choice; - + System.out.println("=== Student Grade Manager ==="); - + while (isRunning) { System.out.println("\n1. Add Grade"); System.out.println("2. View All Grades"); @@ -675,13 +675,13 @@ public class GradeManager { System.out.println("5. Exit"); System.out.print("Choose an option (1-5): "); choice = scanner.nextInt(); - + switch (choice) { case 1: { if (gradeCount < 100) { System.out.print("Enter grade (0-100): "); double newGrade = scanner.nextDouble(); - + if (newGrade >= 0 && newGrade <= 100) { grades[gradeCount] = newGrade; gradeCount++; @@ -720,12 +720,12 @@ public class GradeManager { if (gradeCount > 0) { double highest = grades[0]; double lowest = grades[0]; - + for (int i = 1; i < gradeCount; i++) { if (grades[i] > highest) highest = grades[i]; if (grades[i] < lowest) lowest = grades[i]; } - + System.out.printf("⬆ Highest: %.1f%%\n", highest); System.out.printf("⬇ Lowest: %.1f%%\n", lowest); } else { @@ -740,12 +740,12 @@ public class GradeManager { break; } } - + System.out.println("Thank you for using Grade Manager! "); scanner.close(); } } -```java +``` **Key Concepts:** - Array storage for multiple grades @@ -770,7 +770,7 @@ public class GradeManager { ### Algorithm 4: Unit Converter -```java +``` import java.util.Scanner; public class UnitConverter { @@ -779,9 +779,9 @@ public class UnitConverter { boolean isRunning = true; int conversionType, direction; double value, result; - + System.out.println("=== Unit Converter ==="); - + while (isRunning) { System.out.println("\n1. Temperature (°F ↔ °C)"); System.out.println("2. Length (Feet ↔ Meters)"); @@ -789,7 +789,7 @@ public class UnitConverter { System.out.println("4. Exit"); System.out.print("Select conversion type (1-4): "); conversionType = scanner.nextInt(); - + if (conversionType == 1) { System.out.println("1. °F to °C"); System.out.println("2. °C to °F"); @@ -797,7 +797,7 @@ public class UnitConverter { direction = scanner.nextInt(); System.out.print("Enter temperature: "); value = scanner.nextDouble(); - + if (direction == 1) { result = (value - 32) * 5 / 9; System.out.printf("%.1f°F = %.1f°C\n", value, result); @@ -812,7 +812,7 @@ public class UnitConverter { direction = scanner.nextInt(); System.out.print("Enter length: "); value = scanner.nextDouble(); - + if (direction == 1) { result = value * 0.3048; System.out.printf("%.2f ft = %.2f m\n", value, result); @@ -827,7 +827,7 @@ public class UnitConverter { direction = scanner.nextInt(); System.out.print("Enter weight: "); value = scanner.nextDouble(); - + if (direction == 1) { result = value * 0.4536; System.out.printf("%.2f lbs = %.2f kg\n", value, result); @@ -841,12 +841,12 @@ public class UnitConverter { System.out.println(" Invalid conversion type!"); } } - + System.out.println("Thank you for using Unit Converter! "); scanner.close(); } } -```java +``` **Key Concepts:** - Nested menu system (two levels of choices) @@ -869,7 +869,7 @@ public class UnitConverter { ### Algorithm 5: Survey Data Collector -```java +``` import java.util.Scanner; public class SurveyCollector { @@ -879,9 +879,9 @@ public class SurveyCollector { int responseCount = 0; boolean surveyComplete = false; int rating; - + System.out.println("=== Customer Satisfaction Survey ==="); - + while (!surveyComplete) { System.out.println("\nParticipant #" + (responseCount + 1)); System.out.println("Rate your satisfaction (1-5):"); @@ -892,7 +892,7 @@ public class SurveyCollector { System.out.println("5 = Very Satisfied"); System.out.print("Enter rating (1-5, or 0 to finish survey): "); rating = scanner.nextInt(); - + if (rating == 0) { surveyComplete = true; } else if (rating >= 1 && rating <= 5) { @@ -903,39 +903,39 @@ public class SurveyCollector { System.out.println(" Invalid rating! Please enter 1-5 or 0 to finish."); } } - + if (responseCount > 0) { System.out.println("\n=== Survey Results ==="); System.out.println("Total responses: " + responseCount); - + int[] counts = new int[6]; // Index 0-5, use 1-5 for ratings - + for (int i = 0; i < responseCount; i++) { counts[responses[i]]++; } - + for (int ratingLevel = 1; ratingLevel <= 5; ratingLevel++) { double percentage = (double) counts[ratingLevel] / responseCount * 100; - System.out.printf("%d: %d responses (%.1f%%)\n", + System.out.printf("%d: %d responses (%.1f%%)\n", ratingLevel, counts[ratingLevel], percentage); } - + int sum = 0; for (int i = 0; i < responseCount; i++) { sum += responses[i]; } double average = (double) sum / responseCount; - + System.out.printf("Average satisfaction: %.1f/5.0\n", average); } else { System.out.println("No survey responses collected."); } - + System.out.println("Thank you for participating! "); scanner.close(); } } -```java +``` **Key Concepts:** - Array storage for survey responses @@ -959,7 +959,7 @@ public class SurveyCollector { ### Algorithm 6: Library Book Tracker -```java +``` import java.util.Scanner; public class LibraryTracker { @@ -969,9 +969,9 @@ public class LibraryTracker { int bookCount = 0; boolean isRunning = true; int choice; - + System.out.println("=== Library Book Tracker ==="); - + while (isRunning) { System.out.println("\n1. Add Book"); System.out.println("2. List All Books"); @@ -981,13 +981,13 @@ public class LibraryTracker { System.out.print("Choose option (1-5): "); choice = scanner.nextInt(); scanner.nextLine(); // Consume newline after nextInt() - + switch (choice) { case 1: { if (bookCount < 20) { System.out.print("Enter book title: "); String bookTitle = scanner.nextLine(); - + if (!bookTitle.isEmpty()) { books[bookCount] = bookTitle; bookCount++; @@ -1014,7 +1014,7 @@ public class LibraryTracker { if (bookCount > 0) { System.out.print("Enter search term: "); String searchTerm = scanner.nextLine(); - + int foundCount = 0; for (int i = 0; i < bookCount; i++) { if (books[i].toLowerCase().contains(searchTerm.toLowerCase())) { @@ -1022,7 +1022,7 @@ public class LibraryTracker { foundCount++; } } - + if (foundCount == 0) { System.out.println("ℹ No books found matching '" + searchTerm + "'"); } @@ -1036,15 +1036,15 @@ public class LibraryTracker { System.out.print("Enter book number to remove (1-" + bookCount + "): "); int bookNumber = scanner.nextInt(); scanner.nextLine(); // Consume newline - + if (bookNumber >= 1 && bookNumber <= bookCount) { System.out.println("Removing: '" + books[bookNumber - 1] + "'"); - + // Shift remaining books left for (int i = bookNumber - 1; i < bookCount - 1; i++) { books[i] = books[i + 1]; } - + bookCount--; System.out.println(" Book removed successfully!"); } else { @@ -1063,12 +1063,12 @@ public class LibraryTracker { break; } } - + System.out.println("Thank you for using Library Book Tracker! "); scanner.close(); } } -```java +``` **Key Concepts:** - String array management @@ -1099,19 +1099,19 @@ public class LibraryTracker { ### Advanced Input Techniques in Java **Clearing Scanner Buffer:** -```java +``` // After nextInt(), consume leftover newline scanner.nextInt(); scanner.nextLine(); // Clears the '\n' -```java +``` **Reading Full Lines Safely:** -```java +``` String line = scanner.nextLine().trim(); // Remove leading/trailing whitespace -```java +``` **Input Validation Patterns:** -```java +``` // Numeric range validation with exception handling public static int getValidNumber(Scanner scanner, int min, int max) { while (true) { @@ -1119,7 +1119,7 @@ public static int getValidNumber(Scanner scanner, int min, int max) { System.out.printf("Enter number (%d-%d): ", min, max); int value = scanner.nextInt(); scanner.nextLine(); // Clear buffer - + if (value >= min && value <= max) { return value; } @@ -1130,7 +1130,7 @@ public static int getValidNumber(Scanner scanner, int min, int max) { } } } -```java +``` **Scanner vs BufferedReader:** - Scanner: Easier for mixed types (nextInt, nextDouble, nextLine) @@ -1138,6 +1138,6 @@ public static int getValidNumber(Scanner scanner, int min, int max) { --- - **Excellent! You've mastered user interaction and I/O operations!** + **Excellent! You've mastered user interaction and I/O operations!** *Programs that talk to users are much more useful. Next: Decision-making in pseudocode! ��* diff --git a/lessons/java/stage-2/level-5/lesson.md b/lessons/java/stage-2/level-5/lesson.md index 4b05289..a0fb452 100644 --- a/lessons/java/stage-2/level-5/lesson.md +++ b/lessons/java/stage-2/level-5/lesson.md @@ -49,24 +49,24 @@ Decision-making is the intelligence of programs! Today you'll master complex con ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` javac hello.java ``` 2. **Run your program**: - ```bash + ``` java hello ``` **Expected output:** -```java +``` Hello, World! -```java +``` ## Algorithm 1: Loan Approval System **Pseudocode:** -```java +``` Algorithm: Evaluate Loan Application 1. Display "=== Loan Approval System ===" 2. Display "Enter applicant's age: " @@ -115,7 +115,7 @@ Algorithm: Evaluate Loan Application 22. Else: a. Display " LOAN DENIED" b. Display "Reason: " + approvalStatus -```java +``` **Decision Logic:** - Age restrictions (18-70) @@ -131,7 +131,7 @@ Algorithm: Evaluate Loan Application ## Algorithm 2: Health Risk Assessment **Pseudocode:** -```java +``` Algorithm: Assess Health Risk Factors 1. Display "=== Health Risk Assessment ===" 2. Display "Enter your age: " @@ -190,7 +190,7 @@ Algorithm: Assess Health Risk Factors 37. Else: a. Display " LOW RISK - Maintain healthy lifestyle" b. Display "Recommendations: Continue current healthy habits" -```java +``` **Decision Logic:** - Multi-factor risk assessment @@ -205,7 +205,7 @@ Algorithm: Assess Health Risk Factors ## Algorithm 3: Academic Standing Calculator **Pseudocode:** -```java +``` Algorithm: Determine Academic Standing 1. Display "=== Academic Standing Calculator ===" 2. Display "Enter GPA (0.0-4.0): " @@ -255,7 +255,7 @@ Algorithm: Determine Academic Standing a. Display " Limited eligibility - Academic plan required" 23. Else: a. Display " Counseling required - Contact academic advisor" -```java +``` **Decision Logic:** - Multi-criteria academic evaluation @@ -270,7 +270,7 @@ Algorithm: Determine Academic Standing ## Algorithm 4: Insurance Premium Calculator **Pseudocode:** -```java +``` Algorithm: Calculate Insurance Premium 1. Display "=== Auto Insurance Premium Calculator ===" 2. Display "Enter driver's age: " @@ -324,7 +324,7 @@ Algorithm: Calculate Insurance Premium 36. Else: a. Display " LOW RISK PROFILE" b. Display "Eligible for premium discounts" -```java +``` **Decision Logic:** - Multi-factor risk assessment @@ -339,7 +339,7 @@ Algorithm: Calculate Insurance Premium ## Algorithm 5: Travel Itinerary Planner **Pseudocode:** -```java +``` Algorithm: Plan Travel Itinerary 1. Display "=== Travel Itinerary Planner ===" 2. Display "Enter destination city: " @@ -403,7 +403,7 @@ Algorithm: Plan Travel Itinerary a. Display " Budget exceeded by $" + (totalBudget - dailyBudget × tripDays) 38. Else: a. Display " Within budget - $" + (dailyBudget × tripDays - totalBudget) + " remaining" -```java +``` **Decision Logic:** - Seasonal activity recommendations @@ -418,7 +418,7 @@ Algorithm: Plan Travel Itinerary ## Algorithm 6: Employee Performance Review **Pseudocode:** -```java +``` Algorithm: Evaluate Employee Performance 1. Display "=== Employee Performance Review ===" 2. Display "Enter employee name: " @@ -478,7 +478,7 @@ Algorithm: Evaluate Employee Performance 31. Else: a. Display " Performance review complete" b. Display "Continue professional development" -```java +``` **Decision Logic:** - Multi-criteria performance evaluation @@ -493,7 +493,7 @@ Algorithm: Evaluate Employee Performance ### Decision Tree Patterns **Eligibility Checking:** -```java +``` If primaryCondition && secondaryCondition: If qualifyingFactor: APPROVE @@ -501,19 +501,19 @@ If primaryCondition && secondaryCondition: DENY Else: DENY -```java +``` **Risk Assessment:** -```java +``` Initialize riskScore = 0 For each riskFactor: If factorPresent: Add points to riskScore Categorize based on totalScore -```java +``` **Multi-tier Classification:** -```java +``` If score >= thresholdA: If subCondition: CATEGORY_A_PLUS @@ -523,7 +523,7 @@ Else if score >= thresholdB: CATEGORY_B Else: CATEGORY_C -```java +``` --- @@ -556,7 +556,7 @@ Else: ## Advanced Decision Patterns ### State Machine Concept -```java +``` enum ApplicationState { INITIAL, PROCESSING, @@ -571,10 +571,10 @@ ApplicationState evaluateApplication(ApplicationData data) { if (data.income > 50000 && data.score > 700) return ApplicationState.APPROVED; return ApplicationState.PROCESSING; } -```java +``` ### Rule Engine Pattern -```java +``` int evaluateRules(DataItem item, Rule[] rules) { int score = 0; for (Rule rule : rules) { @@ -584,7 +584,7 @@ int evaluateRules(DataItem item, Rule[] rules) { } return score; } -```java +``` --- @@ -596,7 +596,7 @@ int evaluateRules(DataItem item, Rule[] rules) { ### Algorithm 1: Loan Approval System -```java +``` import java.util.Scanner; public class LoanApproval { @@ -606,7 +606,7 @@ public class LoanApproval { double income, loanAmount; String approvalStatus = "PENDING"; double maxLoanAmount = 0.0; - + System.out.println("=== Loan Approval System ==="); System.out.print("Enter applicant's age: "); age = scanner.nextInt(); @@ -616,7 +616,7 @@ public class LoanApproval { creditScore = scanner.nextInt(); System.out.print("Enter loan amount requested: $"); loanAmount = scanner.nextDouble(); - + if (age < 18) { approvalStatus = "DENIED - Underage"; } else if (age > 70) { @@ -634,7 +634,7 @@ public class LoanApproval { } else { maxLoanAmount = income * 1; } - + if (loanAmount > maxLoanAmount) { approvalStatus = "DENIED - Loan amount exceeds limit"; } else if (loanAmount > income * 0.5) { @@ -644,13 +644,13 @@ public class LoanApproval { } } } - + System.out.println("\n=== Loan Decision ==="); System.out.println("Applicant age: " + age); System.out.printf("Annual income: $%.2f\n", income); System.out.println("Credit score: " + creditScore); System.out.printf("Loan requested: $%.2f\n", loanAmount); - + if (approvalStatus.equals("APPROVED")) { System.out.println(" LOAN APPROVED!"); System.out.printf("Maximum approved amount: $%.2f\n", maxLoanAmount); @@ -661,11 +661,11 @@ public class LoanApproval { System.out.println(" LOAN DENIED"); System.out.println("Reason: " + approvalStatus); } - + scanner.close(); } } -```java +``` **Key Concepts:** - Complex nested conditional logic @@ -687,7 +687,7 @@ public class LoanApproval { ### Algorithm 2: Health Risk Assessment -```java +``` import java.util.Scanner; public class HealthRiskAssessment { @@ -697,7 +697,7 @@ public class HealthRiskAssessment { double bmi; String smokingStatus, exerciseStatus, familyHistory; String riskLevel = "LOW"; - + System.out.println("=== Health Risk Assessment ==="); System.out.print("Enter your age: "); age = scanner.nextInt(); @@ -710,27 +710,27 @@ public class HealthRiskAssessment { exerciseStatus = scanner.nextLine(); System.out.print("Family history of heart disease? (yes/no): "); familyHistory = scanner.nextLine(); - + // Age risk if (age >= 65) riskPoints += 3; else if (age >= 45) riskPoints += 2; else if (age >= 30) riskPoints += 1; - + // BMI risk if (bmi >= 30) riskPoints += 3; else if (bmi >= 25) riskPoints += 2; else if (bmi >= 23) riskPoints += 1; - + // Lifestyle risk if (smokingStatus.equalsIgnoreCase("yes")) riskPoints += 3; if (exerciseStatus.equalsIgnoreCase("no")) riskPoints += 2; if (familyHistory.equalsIgnoreCase("yes")) riskPoints += 2; - + // Determine risk level if (riskPoints >= 8) riskLevel = "HIGH"; else if (riskPoints >= 5) riskLevel = "MODERATE"; else if (riskPoints >= 3) riskLevel = "ELEVATED"; - + System.out.println("\n=== Health Risk Assessment Results ==="); System.out.println("Age: " + age + " years"); System.out.printf("BMI: %.1f\n", bmi); @@ -739,7 +739,7 @@ public class HealthRiskAssessment { System.out.println("Family history: " + familyHistory); System.out.println("Risk points: " + riskPoints + "/12"); System.out.println("Risk level: " + riskLevel); - + if (riskLevel.equals("HIGH")) { System.out.println(" HIGH RISK - Consult doctor immediately"); System.out.println("Recommendations: Lifestyle changes, medical evaluation"); @@ -753,11 +753,11 @@ public class HealthRiskAssessment { System.out.println(" LOW RISK - Maintain healthy lifestyle"); System.out.println("Recommendations: Continue current healthy habits"); } - + scanner.close(); } } -```java +``` **Key Concepts:** - Point-based risk assessment system @@ -779,7 +779,7 @@ public class HealthRiskAssessment { ### Algorithm 3: Academic Standing Calculator -```java +``` import java.util.Scanner; public class AcademicStanding { @@ -790,7 +790,7 @@ public class AcademicStanding { String probationStatus; String standing = "UNDETERMINED"; String eligibilityStatus = "ELIGIBLE"; - + System.out.println("=== Academic Standing Calculator ==="); System.out.print("Enter GPA (0.0-4.0): "); gpa = scanner.nextDouble(); @@ -801,7 +801,7 @@ public class AcademicStanding { scanner.nextLine(); // Consume newline System.out.print("Any academic probation? (yes/no): "); probationStatus = scanner.nextLine(); - + if (probationStatus.equalsIgnoreCase("yes")) { standing = "ACADEMIC PROBATION"; eligibilityStatus = "RESTRICTED"; @@ -829,7 +829,7 @@ public class AcademicStanding { eligibilityStatus = "COUNSELING REQUIRED"; } } - + System.out.println("\n=== Academic Assessment ==="); System.out.printf("GPA: %.2f\n", gpa); System.out.println("Credit Hours: " + creditHours); @@ -837,7 +837,7 @@ public class AcademicStanding { System.out.println("Probation Status: " + probationStatus); System.out.println("Academic Standing: " + standing); System.out.println("Eligibility Status: " + eligibilityStatus); - + if (eligibilityStatus.equals("ELIGIBLE")) { System.out.println(" Eligible for all academic activities"); } else if (eligibilityStatus.equals("RESTRICTED")) { @@ -845,11 +845,11 @@ public class AcademicStanding { } else { System.out.println(" Counseling required - Contact academic advisor"); } - + scanner.close(); } } -```java +``` **Key Concepts:** - Multi-criteria academic evaluation @@ -868,7 +868,7 @@ public class AcademicStanding { ### Algorithm 4: Insurance Premium Calculator -```java +``` import java.util.Scanner; public class InsurancePremium { @@ -877,7 +877,7 @@ public class InsurancePremium { int age, experience, mileage; String vehicleType, accidentHistory; double basePremium = 500.0, riskMultiplier = 1.0, finalPremium; - + System.out.println("=== Auto Insurance Premium Calculator ==="); System.out.print("Enter driver's age: "); age = scanner.nextInt(); @@ -890,29 +890,29 @@ public class InsurancePremium { accidentHistory = scanner.nextLine(); System.out.print("Annual mileage: "); mileage = scanner.nextInt(); - + // Age risk if (age < 25) riskMultiplier *= 1.5; else if (age > 65) riskMultiplier *= 1.2; - + // Experience risk if (experience < 3) riskMultiplier *= 1.4; else if (experience > 10) riskMultiplier *= 0.9; - + // Vehicle type risk if (vehicleType.equalsIgnoreCase("sports")) riskMultiplier *= 1.8; else if (vehicleType.equalsIgnoreCase("suv")) riskMultiplier *= 1.3; else if (vehicleType.equalsIgnoreCase("truck")) riskMultiplier *= 1.1; - + // Accident history if (accidentHistory.equalsIgnoreCase("yes")) riskMultiplier *= 1.6; - + // Mileage risk if (mileage > 15000) riskMultiplier *= 1.2; else if (mileage < 5000) riskMultiplier *= 0.95; - + finalPremium = basePremium * riskMultiplier; - + System.out.println("\n=== Premium Calculation ==="); System.out.println("Driver Age: " + age); System.out.println("Driving Experience: " + experience + " years"); @@ -922,7 +922,7 @@ public class InsurancePremium { System.out.printf("Base Premium: $%.2f\n", basePremium); System.out.printf("Risk Multiplier: %.2f\n", riskMultiplier); System.out.printf("Final Premium: $%.2f\n", finalPremium); - + if (riskMultiplier > 2.0) { System.out.println(" HIGH RISK PROFILE"); System.out.println("Consider defensive driving courses"); @@ -933,11 +933,11 @@ public class InsurancePremium { System.out.println(" LOW RISK PROFILE"); System.out.println("Eligible for premium discounts"); } - + scanner.close(); } } -```java +``` **Key Concepts:** - Cumulative risk multiplier system (*= operator) @@ -959,7 +959,7 @@ public class InsurancePremium { ### Algorithm 5: Travel Itinerary Planner -```java +``` import java.util.Scanner; public class TravelPlanner { @@ -969,7 +969,7 @@ public class TravelPlanner { int tripDays, groupSize, activityCount = 0; double dailyBudget, totalCost = 0.0; double accommodationCost, foodCost, activityCost, transportationCost, miscellaneousCost, totalBudget; - + System.out.println("=== Travel Itinerary Planner ==="); System.out.print("Enter destination city: "); destination = scanner.nextLine(); @@ -982,7 +982,7 @@ public class TravelPlanner { season = scanner.nextLine(); System.out.print("Group size: "); groupSize = scanner.nextInt(); - + // Seasonal activity planning if (season.equalsIgnoreCase("summer")) { if (destination.toLowerCase().contains("beach")) { @@ -1009,7 +1009,7 @@ public class TravelPlanner { totalCost += 35; activityCount = 4; } - + // Cost calculations accommodationCost = dailyBudget * 0.4 * tripDays; foodCost = dailyBudget * 0.3 * tripDays; @@ -1017,14 +1017,14 @@ public class TravelPlanner { transportationCost = dailyBudget * 0.2 * tripDays; miscellaneousCost = dailyBudget * 0.1 * tripDays; totalBudget = accommodationCost + foodCost + activityCost + transportationCost + miscellaneousCost; - + // Group discount if (groupSize > 4) { double groupDiscount = totalBudget * 0.1; totalBudget -= groupDiscount; System.out.printf(" Group discount applied: $%.2f\n", groupDiscount); } - + System.out.println("\n=== Travel Itinerary ==="); System.out.println("Destination: " + destination); System.out.println("Duration: " + tripDays + " days"); @@ -1038,18 +1038,18 @@ public class TravelPlanner { System.out.printf("Transportation: $%.2f\n", transportationCost); System.out.printf("Miscellaneous: $%.2f\n", miscellaneousCost); System.out.printf("Total Estimated Cost: $%.2f\n", totalBudget); - + double budgetLimit = dailyBudget * tripDays; if (totalBudget > budgetLimit) { System.out.printf(" Budget exceeded by $%.2f\n", totalBudget - budgetLimit); } else { System.out.printf(" Within budget - $%.2f remaining\n", budgetLimit - totalBudget); } - + scanner.close(); } } -```java +``` **Key Concepts:** - Seasonal activity recommendations (nested if for season + destination) @@ -1072,7 +1072,7 @@ public class TravelPlanner { ### Algorithm 6: Employee Performance Review -```java +``` import java.util.Scanner; public class PerformanceReview { @@ -1082,7 +1082,7 @@ public class PerformanceReview { int yearsService, productivity, quality, teamwork; double averageScore, salaryAdjustment = 0.0; String performanceRating = "UNDETERMINED"; - + System.out.println("=== Employee Performance Review ==="); System.out.print("Enter employee name: "); employeeName = scanner.nextLine(); @@ -1097,9 +1097,9 @@ public class PerformanceReview { scanner.nextLine(); // Consume newline System.out.print("Any disciplinary actions? (yes/no): "); disciplinaryStatus = scanner.nextLine(); - + averageScore = (productivity + quality + teamwork) / 3.0; - + if (disciplinaryStatus.equalsIgnoreCase("yes")) { performanceRating = "UNSATISFACTORY"; salaryAdjustment = -5.0; @@ -1126,7 +1126,7 @@ public class PerformanceReview { salaryAdjustment = 0.0; } } - + System.out.println("\n=== Performance Review Results ==="); System.out.println("Employee: " + employeeName); System.out.println("Years of Service: " + yearsService); @@ -1137,7 +1137,7 @@ public class PerformanceReview { System.out.println("Disciplinary Actions: " + disciplinaryStatus); System.out.println("Performance Rating: " + performanceRating); System.out.printf("Salary Adjustment: %.1f%%\n", salaryAdjustment); - + if (performanceRating.equals("OUTSTANDING")) { System.out.println(" EMPLOYEE OF THE YEAR CANDIDATE"); System.out.println("Eligible for bonus and promotion consideration"); @@ -1148,11 +1148,11 @@ public class PerformanceReview { System.out.println(" Performance review complete"); System.out.println("Continue professional development"); } - + scanner.close(); } } -```java +``` **Key Concepts:** - Multi-criteria performance evaluation (three scores averaged) @@ -1180,7 +1180,7 @@ public class PerformanceReview { ### Decision Logic Best Practices in Java **Readable Conditions:** -```java +``` // Good - clear and readable if (age >= 18 && age <= 65 && income > 30000) { // approve @@ -1194,10 +1194,10 @@ if (age >= 18) { } } } -```java +``` **Consistent Structure:** -```java +``` // Use consistent patterns if (condition1) { // handle case 1 @@ -1206,10 +1206,10 @@ if (condition1) { } else { // handle default case } -```java +``` **Early Returns (in methods):** -```java +``` // Good - fail fast public void processApplication(int age, double income) { if (age < 18) { @@ -1218,10 +1218,10 @@ public void processApplication(int age, double income) { } // continue with valid input } -```java +``` **Enum for States:** -```java +``` enum RiskLevel { LOW, ELEVATED, MODERATE, HIGH } @@ -1230,10 +1230,10 @@ RiskLevel level = RiskLevel.LOW; if (riskPoints >= 8) level = RiskLevel.HIGH; else if (riskPoints >= 5) level = RiskLevel.MODERATE; else if (riskPoints >= 3) level = RiskLevel.ELEVATED; -```java +``` --- - **Brilliant! You've mastered complex decision-making in code!** + **Brilliant! You've mastered complex decision-making in code!** *Programs can now make intelligent decisions like real applications. Next: Loop algorithms in pseudocode! * diff --git a/lessons/java/stage-2/level-6/lesson.md b/lessons/java/stage-2/level-6/lesson.md index 15ba14e..431551d 100644 --- a/lessons/java/stage-2/level-6/lesson.md +++ b/lessons/java/stage-2/level-6/lesson.md @@ -49,24 +49,24 @@ Loops are the workhorses of programming! Today you'll master algorithms that use ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` javac hello.java ``` 2. **Run your program**: - ```bash + ``` java hello ``` **Expected output:** -```java +``` Hello, World! -```java +``` ## Algorithm 1: Sales Data Analyzer **Pseudocode:** -```java +``` Algorithm: Analyze Monthly Sales Data 1. Display "=== Sales Data Analyzer ===" 2. Initialize sales array (can hold 30 values) @@ -103,7 +103,7 @@ Algorithm: Analyze Monthly Sales Data i. Display "Day " + (i + 1) + ": $" + sales[i] 10. Else: a. Display "No sales data entered." -```java +``` **Loop Logic:** - Input loop with validation @@ -118,7 +118,7 @@ Algorithm: Analyze Monthly Sales Data ## Algorithm 2: Student Attendance Tracker **Pseudocode:** -```java +``` Algorithm: Track Class Attendance 1. Display "=== Class Attendance Tracker ===" 2. Display "Enter number of students: " @@ -151,7 +151,7 @@ Algorithm: Track Class Attendance i. Display "Student " + student + ": Present" b. Else: i. Display "Student " + student + ": Absent" -```java +``` **Loop Logic:** - Fixed iteration for known number of students @@ -166,7 +166,7 @@ Algorithm: Track Class Attendance ## Algorithm 3: Inventory Management System **Pseudocode:** -```java +``` Algorithm: Manage Store Inventory 1. Display "=== Inventory Management System ===" 2. Initialize itemNames array (can hold 50 items) @@ -240,7 +240,7 @@ Algorithm: Manage Store Inventory i. Else: i. Display " Invalid choice!" 7. Display "Thank you for using Inventory Management System! " -```java +``` **Loop Logic:** - Menu-driven interface with multiple operations @@ -255,7 +255,7 @@ Algorithm: Manage Store Inventory ## Algorithm 4: Grade Book Calculator **Pseudocode:** -```java +``` Algorithm: Calculate Final Grades 1. Display "=== Grade Book Calculator ===" 2. Display "Enter number of students: " @@ -312,7 +312,7 @@ Algorithm: Calculate Final Grades 23. Display "C grades: " + gradeRanges[2] 24. Display "D grades: " + gradeRanges[3] 25. Display "F grades: " + gradeRanges[4] -```java +``` **Loop Logic:** - 2D array processing (nested loops) @@ -327,7 +327,7 @@ Algorithm: Calculate Final Grades ## Algorithm 5: Password Generator **Pseudocode:** -```java +``` Algorithm: Generate Secure Passwords 1. Display "=== Password Generator ===" 2. Display "Enter desired password length (8-20): " @@ -365,7 +365,7 @@ Algorithm: Generate Secure Passwords 23. If includeSpecial is "y": a. Display " Special characters" 24. Display " Lowercase letters (always included)" -```java +``` **Loop Logic:** - Input validation loop @@ -380,7 +380,7 @@ Algorithm: Generate Secure Passwords ## Algorithm 6: Voting System **Pseudocode:** -```java +``` Algorithm: Conduct Election Voting 1. Display "=== Election Voting System ===" 2. Initialize candidateNames array ["Alice", "Bob", "Charlie"] @@ -425,7 +425,7 @@ Algorithm: Conduct Election Voting ii. Display candidateNames[i] + ": " + votes[i] + " votes (" + percentage + "%)" 8. Else: a. Display "No votes were cast." -```java +``` **Loop Logic:** - Menu-driven voting interface @@ -483,25 +483,25 @@ Algorithm: Conduct Election Voting ## Loop Algorithm Patterns ### Accumulation Pattern -```java +``` Initialize total to 0 While getting values: Get nextValue Add nextValue to total Display "Total: " + total -```java +``` ### Counting Pattern -```java +``` Initialize count to 0 For each item: If item meets criteria: Add 1 to count Display "Count: " + count -```java +``` ### Search Pattern -```java +``` Initialize found to false For each item in collection: If item matches target: @@ -512,10 +512,10 @@ If found: Display "Found at location" Else: Display "Not found" -```java +``` ### Validation Pattern -```java +``` Initialize isValid to false While not isValid: Get userInput @@ -524,7 +524,7 @@ While not isValid: Else: Display error message Process valid input -```java +``` --- @@ -536,7 +536,7 @@ Process valid input ### Algorithm 1: Sales Data Analyzer -```java +``` import java.util.Scanner; public class SalesAnalyzer { @@ -545,21 +545,21 @@ public class SalesAnalyzer { double[] sales = new double[30]; int salesCount = 0; double totalSales = 0.0, highestSale = 0.0, lowestSale = 999999.0; - + System.out.println("=== Sales Data Analyzer ==="); System.out.println("Enter daily sales (enter -1 to finish):"); - + while (salesCount < 30) { System.out.print("Day " + (salesCount + 1) + ": $"); double dailySale = scanner.nextDouble(); - + if (dailySale == -1) { break; } else if (dailySale >= 0) { sales[salesCount] = dailySale; totalSales += dailySale; salesCount++; - + if (dailySale > highestSale) { highestSale = dailySale; } @@ -570,17 +570,17 @@ public class SalesAnalyzer { System.out.println(" Invalid sale amount! Please enter positive number."); } } - + if (salesCount > 0) { double averageSale = totalSales / salesCount; - + System.out.println("\n=== Sales Summary ==="); System.out.println("Total days: " + salesCount); System.out.printf("Total sales: $%.2f\n", totalSales); System.out.printf("Average daily sales: $%.2f\n", averageSale); System.out.printf("Highest sale: $%.2f\n", highestSale); System.out.printf("Lowest sale: $%.2f\n", lowestSale); - + System.out.println("\n=== Daily Breakdown ==="); for (int i = 0; i < salesCount; i++) { System.out.printf("Day %d: $%.2f\n", i + 1, sales[i]); @@ -588,11 +588,11 @@ public class SalesAnalyzer { } else { System.out.println("No sales data entered."); } - + scanner.close(); } } -```java +``` **Key Concepts:** - Array storage for sales data @@ -615,25 +615,25 @@ public class SalesAnalyzer { ### Algorithm 2: Student Attendance Tracker -```java +``` import java.util.Scanner; public class AttendanceTracker { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int numStudents, presentCount = 0; - + System.out.println("=== Class Attendance Tracker ==="); System.out.print("Enter number of students: "); numStudents = scanner.nextInt(); scanner.nextLine(); // Consume newline - + boolean[] attendance = new boolean[numStudents]; - + for (int student = 1; student <= numStudents; student++) { System.out.print("Student " + student + " present? (y/n): "); String attendanceStatus = scanner.nextLine(); - + if (attendanceStatus.equalsIgnoreCase("y")) { attendance[student - 1] = true; presentCount++; @@ -641,15 +641,15 @@ public class AttendanceTracker { attendance[student - 1] = false; } } - + double attendancePercentage = (double) presentCount / numStudents * 100; - + System.out.println("\n=== Attendance Report ==="); System.out.println("Total students: " + numStudents); System.out.println("Present: " + presentCount); System.out.println("Absent: " + (numStudents - presentCount)); System.out.printf("Attendance rate: %.1f%%\n", attendancePercentage); - + if (attendancePercentage >= 90) { System.out.println(" Excellent attendance!"); } else if (attendancePercentage >= 75) { @@ -657,7 +657,7 @@ public class AttendanceTracker { } else { System.out.println(" Poor attendance - follow up required"); } - + System.out.println("\n=== Individual Status ==="); for (int student = 1; student <= numStudents; student++) { if (attendance[student - 1]) { @@ -666,11 +666,11 @@ public class AttendanceTracker { System.out.println("Student " + student + ": Absent"); } } - + scanner.close(); } } -```java +``` **Key Concepts:** - Fixed iteration for known number of students (for loop) @@ -692,7 +692,7 @@ public class AttendanceTracker { ### Algorithm 3: Inventory Management System -```java +``` import java.util.Scanner; public class InventoryManager { @@ -703,9 +703,9 @@ public class InventoryManager { int itemCount = 0; boolean isRunning = true; int choice; - + System.out.println("=== Inventory Management System ==="); - + while (isRunning) { System.out.println("\n1. Add Item"); System.out.println("2. Update Quantity"); @@ -715,7 +715,7 @@ public class InventoryManager { System.out.print("Choose option (1-5): "); choice = scanner.nextInt(); scanner.nextLine(); // Consume newline - + switch (choice) { case 1: { if (itemCount < 50) { @@ -724,7 +724,7 @@ public class InventoryManager { System.out.print("Enter initial quantity: "); int newQuantity = scanner.nextInt(); scanner.nextLine(); // Consume newline - + if (newQuantity >= 0) { itemNames[itemCount] = newItemName; itemQuantities[itemCount] = newQuantity; @@ -742,7 +742,7 @@ public class InventoryManager { if (itemCount > 0) { System.out.print("Enter item name to update: "); String searchName = scanner.nextLine(); - + boolean found = false; for (int i = 0; i < itemCount; i++) { if (itemNames[i].equalsIgnoreCase(searchName)) { @@ -750,7 +750,7 @@ public class InventoryManager { System.out.print("Enter new quantity: "); int newQuantity = scanner.nextInt(); scanner.nextLine(); // Consume newline - + if (newQuantity >= 0) { itemQuantities[i] = newQuantity; System.out.println(" Quantity updated!"); @@ -761,7 +761,7 @@ public class InventoryManager { break; } } - + if (!found) { System.out.println(" Item not found!"); } @@ -784,14 +784,14 @@ public class InventoryManager { if (itemCount > 0) { System.out.println("=== Low Stock Alert (≤5 units) ==="); int lowStockCount = 0; - + for (int i = 0; i < itemCount; i++) { if (itemQuantities[i] <= 5) { System.out.println(itemNames[i] + ": " + itemQuantities[i] + " units "); lowStockCount++; } } - + if (lowStockCount == 0) { System.out.println(" All items have sufficient stock."); } @@ -807,12 +807,12 @@ public class InventoryManager { break; } } - + System.out.println("Thank you for using Inventory Management System! "); scanner.close(); } } -```java +``` **Key Concepts:** - Parallel arrays (itemNames and itemQuantities at same indices) @@ -836,57 +836,57 @@ public class InventoryManager { ### Algorithm 4: Grade Book Calculator -```java +``` import java.util.Scanner; public class GradeBook { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int numStudents, numAssignments; - + System.out.println("=== Grade Book Calculator ==="); System.out.print("Enter number of students: "); numStudents = scanner.nextInt(); System.out.print("Enter number of assignments: "); numAssignments = scanner.nextInt(); scanner.nextLine(); // Consume newline - + String[] studentNames = new String[numStudents]; double[][] grades = new double[numStudents][numAssignments]; - + // Input student data for (int student = 0; student < numStudents; student++) { System.out.print("Enter name for student " + (student + 1) + ": "); studentNames[student] = scanner.nextLine(); - + double studentTotal = 0.0; for (int assignment = 0; assignment < numAssignments; assignment++) { - System.out.print("Enter grade for " + studentNames[student] + + System.out.print("Enter grade for " + studentNames[student] + " assignment " + (assignment + 1) + ": "); grades[student][assignment] = scanner.nextDouble(); studentTotal += grades[student][assignment]; } scanner.nextLine(); // Consume newline after grades - + double studentAverage = studentTotal / numAssignments; System.out.printf("%s's average: %.1f\n", studentNames[student], studentAverage); } - + // Calculate class statistics System.out.println("\n=== Class Statistics ==="); double classTotal = 0.0; double highestAverage = 0.0; double lowestAverage = 100.0; - + for (int student = 0; student < numStudents; student++) { double studentTotal = 0.0; for (int assignment = 0; assignment < numAssignments; assignment++) { studentTotal += grades[student][assignment]; } - + double studentAverage = studentTotal / numAssignments; classTotal += studentAverage; - + if (studentAverage > highestAverage) { highestAverage = studentAverage; } @@ -894,41 +894,41 @@ public class GradeBook { lowestAverage = studentAverage; } } - + double classAverage = classTotal / numStudents; System.out.printf("Class average: %.1f\n", classAverage); System.out.printf("Highest student average: %.1f\n", highestAverage); System.out.printf("Lowest student average: %.1f\n", lowestAverage); - + // Grade distribution System.out.println("\n=== Grade Distribution ==="); int[] gradeRanges = new int[5]; // A, B, C, D, F - + for (int student = 0; student < numStudents; student++) { double studentTotal = 0.0; for (int assignment = 0; assignment < numAssignments; assignment++) { studentTotal += grades[student][assignment]; } - + double studentAverage = studentTotal / numAssignments; - + if (studentAverage >= 90) gradeRanges[0]++; else if (studentAverage >= 80) gradeRanges[1]++; else if (studentAverage >= 70) gradeRanges[2]++; else if (studentAverage >= 60) gradeRanges[3]++; else gradeRanges[4]++; } - + System.out.println("A grades: " + gradeRanges[0]); System.out.println("B grades: " + gradeRanges[1]); System.out.println("C grades: " + gradeRanges[2]); System.out.println("D grades: " + gradeRanges[3]); System.out.println("F grades: " + gradeRanges[4]); - + scanner.close(); } } -```java +``` **Key Concepts:** - 2D array processing with nested loops (rows=students, cols=assignments) @@ -957,7 +957,7 @@ public class GradeBook { ### Algorithm 5: Password Generator -```java +``` import java.util.Scanner; import java.util.Random; import java.util.ArrayList; @@ -967,36 +967,36 @@ public class PasswordGenerator { Scanner scanner = new Scanner(System.in); Random random = new Random(); int passwordLength; - + System.out.println("=== Password Generator ==="); System.out.print("Enter desired password length (8-20): "); passwordLength = scanner.nextInt(); scanner.nextLine(); // Consume newline - + while (passwordLength < 8 || passwordLength > 20) { System.out.println(" Length must be between 8-20 characters!"); System.out.print("Enter desired password length (8-20): "); passwordLength = scanner.nextInt(); scanner.nextLine(); } - + System.out.print("Include uppercase letters? (y/n): "); String includeUpper = scanner.nextLine(); System.out.print("Include numbers? (y/n): "); String includeNumbers = scanner.nextLine(); System.out.print("Include special characters? (y/n): "); String includeSpecial = scanner.nextLine(); - + // Character sets String lowercase = "abcdefghijklmnopqrstuvwxyz"; String uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; String numbers = "0123456789"; String special = "!@#$%^&*()_+-=[]{}|;:,.<>?"; - + // Build available character sets ArrayList charSets = new ArrayList<>(); charSets.add(lowercase); // Always include lowercase - + if (includeUpper.equalsIgnoreCase("y")) { charSets.add(uppercase); } @@ -1006,19 +1006,19 @@ public class PasswordGenerator { if (includeSpecial.equalsIgnoreCase("y")) { charSets.add(special); } - + // Generate password StringBuilder password = new StringBuilder(); for (int i = 0; i < passwordLength; i++) { // Pick random character set int setIndex = random.nextInt(charSets.size()); String selectedSet = charSets.get(setIndex); - + // Pick random character from set int charIndex = random.nextInt(selectedSet.length()); password.append(selectedSet.charAt(charIndex)); } - + System.out.println("Generated Password: " + password.toString()); System.out.println("Password length: " + passwordLength); System.out.println("Character sets used:"); @@ -1032,11 +1032,11 @@ public class PasswordGenerator { System.out.println(" Special characters"); } System.out.println(" Lowercase letters (always included)"); - + scanner.close(); } } -```java +``` **Key Concepts:** - Input validation loop (while with compound condition) @@ -1065,7 +1065,7 @@ public class PasswordGenerator { ### Algorithm 6: Voting System -```java +``` import java.util.Scanner; public class VotingSystem { @@ -1076,9 +1076,9 @@ public class VotingSystem { int totalVotes = 0; boolean votingActive = true; int choice; - + System.out.println("=== Election Voting System ==="); - + while (votingActive) { System.out.println("\n=== Vote Menu ==="); System.out.println("Candidates:"); @@ -1089,7 +1089,7 @@ public class VotingSystem { System.out.println("5. End Voting"); System.out.print("Enter your choice (1-5): "); choice = scanner.nextInt(); - + if (choice >= 1 && choice <= 3) { votes[choice - 1]++; totalVotes++; @@ -1097,11 +1097,11 @@ public class VotingSystem { } else if (choice == 4) { System.out.println("=== Current Results ==="); System.out.println("Total votes: " + totalVotes); - + if (totalVotes > 0) { for (int i = 0; i < 3; i++) { double percentage = (double) votes[i] / totalVotes * 100; - System.out.printf("%s: %d votes (%.1f%%)\n", + System.out.printf("%s: %d votes (%.1f%%)\n", candidateNames[i], votes[i], percentage); } } else { @@ -1113,38 +1113,38 @@ public class VotingSystem { System.out.println(" Invalid choice!"); } } - + if (totalVotes > 0) { System.out.println("\n=== Final Election Results ==="); - + // Find winner int winnerIndex = 0; int maxVotes = votes[0]; - + for (int i = 1; i < 3; i++) { if (votes[i] > maxVotes) { maxVotes = votes[i]; winnerIndex = i; } } - - System.out.println(" Winner: " + candidateNames[winnerIndex] + + + System.out.println(" Winner: " + candidateNames[winnerIndex] + " with " + maxVotes + " votes!"); System.out.println("Total votes cast: " + totalVotes); - + for (int i = 0; i < 3; i++) { double percentage = (double) votes[i] / totalVotes * 100; - System.out.printf("%s: %d votes (%.1f%%)\n", + System.out.printf("%s: %d votes (%.1f%%)\n", candidateNames[i], votes[i], percentage); } } else { System.out.println("No votes were cast."); } - + scanner.close(); } } -```java +``` **Key Concepts:** - Menu-driven voting interface with while loop @@ -1174,7 +1174,7 @@ public class VotingSystem { ### Loop Efficiency Considerations in Java **Array Processing:** -```java +``` // Efficient - single pass for (int i = 0; i < size; i++) { total += array[i]; @@ -1188,10 +1188,10 @@ for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) { if (array[i] > max) max = array[i]; } -```java +``` **Early Termination:** -```java +``` // Good - stop when found for (int i = 0; i < size; i++) { if (array[i] == target) { @@ -1199,10 +1199,10 @@ for (int i = 0; i < size; i++) { break; // Don't continue searching } } -```java +``` **Enhanced For Loop:** -```java +``` // For iteration (no index needed) for (String name : studentNames) { System.out.println(name); @@ -1212,10 +1212,10 @@ for (String name : studentNames) { for (int i = 0; i < studentNames.length; i++) { System.out.println((i + 1) + ". " + studentNames[i]); } -```java +``` --- - **Fantastic! You've mastered loop-based algorithms!** + **Fantastic! You've mastered loop-based algorithms!** *Loops are the engines of computation. Next: Function pseudocode for modular programming! * diff --git a/lessons/java/stage-2/level-7/lesson.md b/lessons/java/stage-2/level-7/lesson.md index c378cb7..329ce95 100644 --- a/lessons/java/stage-2/level-7/lesson.md +++ b/lessons/java/stage-2/level-7/lesson.md @@ -49,24 +49,24 @@ Functions (methods in Java) are the building blocks of organized code! Today you ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` javac hello.java ``` 2. **Run your program**: - ```bash + ``` java hello ``` **Expected output:** -```java +``` Hello, World! -```java +``` ## Algorithm 1: Calculator Program with Methods **Pseudocode:** -```java +``` Algorithm: Modular Calculator Program Method: displayMenu() @@ -129,7 +129,7 @@ Main Algorithm: e. Else: i. Display " Invalid choice!" 4. Display "Thank you for using the calculator! " -```java +``` **Method Design:** - `displayMenu()`: Handles UI display @@ -144,7 +144,7 @@ Main Algorithm: ## Algorithm 2: Student Grade Management System **Pseudocode:** -```java +``` Algorithm: Student Grade Management with Methods Method: displayMainMenu() @@ -230,7 +230,7 @@ Main Algorithm: h. Else: i. Display " Invalid choice!" 7. Display "Thank you for using Grade Management System! " -```java +``` **Method Design:** - `displayMainMenu()`: UI method @@ -246,7 +246,7 @@ Main Algorithm: ## Algorithm 3: Banking System with Methods **Pseudocode:** -```java +``` Algorithm: Simple Banking System with Methods Method: displayBankMenu() @@ -331,7 +331,7 @@ Main Algorithm: h. Else: i. Display " Invalid choice!" 7. Display "Thank you for banking with us! " -```java +``` **Method Design:** - `displayBankMenu()`: UI method @@ -346,7 +346,7 @@ Main Algorithm: ## Algorithm 4: Statistics Calculator with Methods **Pseudocode:** -```java +``` Algorithm: Statistical Analysis with Methods Method: displayStatsMenu() @@ -451,7 +451,7 @@ Main Algorithm: i. Else: i. Display " Invalid choice!" 6. Display "Thank you for using Statistics Calculator! " -```java +``` **Method Design:** - `displayStatsMenu()`: UI method @@ -466,7 +466,7 @@ Main Algorithm: ## Algorithm 5: Text Analyzer with Methods **Pseudocode:** -```java +``` Algorithm: Text Analysis with Methods Method: displayTextMenu() @@ -558,7 +558,7 @@ Main Algorithm: j. Else: i. Display " Invalid choice!" 5. Display "Thank you for using Text Analyzer! " -```java +``` **Method Design:** - `displayTextMenu()`: UI method @@ -620,7 +620,7 @@ Main Algorithm: ## Method Design Patterns ### Input-Process-Output Pattern -```java +``` Method: getUserInput(scanner, prompt) Display prompt Get and return input @@ -631,10 +631,10 @@ Method: processData(data) Method: displayOutput(result) Format and display result -```java +``` ### Validation Pattern -```java +``` Method: isValid(value, min, max) Return value >= min && value <= max @@ -645,10 +645,10 @@ Method: getValidInput(scanner, prompt, min, max) If isValid(input, min, max): Return input Display error message -```java +``` ### Calculation with Helper Pattern -```java +``` Method: calculateTotal(items, count) Sum = 0 For i from 0 to count: @@ -657,7 +657,7 @@ Method: calculateTotal(items, count) Method: calculateItemValue(item) Return item.price * item.quantity -```java +``` --- @@ -669,11 +669,11 @@ Method: calculateItemValue(item) ### Algorithm 1: Calculator Program with Methods -```java +``` import java.util.Scanner; public class ModularCalculator { - + public static void displayMenu() { System.out.println("\n=== Calculator Menu ==="); System.out.println("1. Addition"); @@ -683,24 +683,24 @@ public class ModularCalculator { System.out.println("5. Exit"); System.out.print("Choose operation (1-5): "); } - + public static double getNumber(Scanner scanner, String prompt) { System.out.print(prompt); return scanner.nextDouble(); } - + public static double performAddition(double a, double b) { return a + b; } - + public static double performSubtraction(double a, double b) { return a - b; } - + public static double performMultiplication(double a, double b) { return a * b; } - + public static double performDivision(double a, double b) { if (b == 0) { System.out.println(" Error: Division by zero!"); @@ -709,24 +709,24 @@ public class ModularCalculator { return a / b; } } - + public static void displayResult(String operation, double a, double b, double result) { System.out.printf("Result: %.2f %s %.2f = %.2f\n", a, operation, b, result); } - + public static void main(String[] args) { Scanner scanner = new Scanner(System.in); boolean running = true; - + while (running) { displayMenu(); int choice = scanner.nextInt(); - + if (choice >= 1 && choice <= 4) { double num1 = getNumber(scanner, "Enter first number: "); double num2 = getNumber(scanner, "Enter second number: "); double result; - + switch (choice) { case 1: result = performAddition(num1, num2); @@ -753,12 +753,12 @@ public class ModularCalculator { System.out.println(" Invalid choice!"); } } - + System.out.println("Thank you for using the calculator! "); scanner.close(); } } -```java +``` **Key Concepts:** - Static methods for utility functions (no instance needed) @@ -781,11 +781,11 @@ public class ModularCalculator { ### Algorithm 2: Student Grade Management System -```java +``` import java.util.Scanner; public class GradeManagement { - + public static void displayMainMenu() { System.out.println("\n=== Grade Management System ==="); System.out.println("1. Add Student"); @@ -795,7 +795,7 @@ public class GradeManagement { System.out.println("5. Exit"); System.out.print("Choose option (1-5): "); } - + public static int addStudent(String[] students, double[] grades, int count, Scanner scanner) { if (count < 50) { scanner.nextLine(); // Consume newline @@ -803,7 +803,7 @@ public class GradeManagement { String name = scanner.nextLine(); System.out.print("Enter grade (0-100): "); double grade = scanner.nextDouble(); - + if (grade >= 0 && grade <= 100) { students[count] = name; grades[count] = grade; @@ -818,7 +818,7 @@ public class GradeManagement { return count; } } - + public static void displayAllStudents(String[] students, double[] grades, int count) { if (count > 0) { System.out.println("\n=== Student List ==="); @@ -829,7 +829,7 @@ public class GradeManagement { System.out.println("ℹ No students in the system."); } } - + public static double calculateClassAverage(double[] grades, int count) { if (count > 0) { double sum = 0; @@ -841,36 +841,36 @@ public class GradeManagement { return 0; } } - + public static void findTopPerformer(String[] students, double[] grades, int count) { if (count > 0) { double maxGrade = grades[0]; String topStudent = students[0]; - + for (int i = 1; i < count; i++) { if (grades[i] > maxGrade) { maxGrade = grades[i]; topStudent = students[i]; } } - + System.out.printf(" Top Performer: %s (%.1f%%)\n", topStudent, maxGrade); } else { System.out.println("ℹ No students in the system."); } } - + public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String[] students = new String[50]; double[] grades = new double[50]; int studentCount = 0; boolean running = true; - + while (running) { displayMainMenu(); int choice = scanner.nextInt(); - + switch (choice) { case 1: studentCount = addStudent(students, grades, studentCount, scanner); @@ -897,12 +897,12 @@ public class GradeManagement { break; } } - + System.out.println("Thank you for using Grade Management System! "); scanner.close(); } } -```java +``` **Key Concepts:** - Methods modifying arrays (arrays passed by reference) @@ -924,11 +924,11 @@ public class GradeManagement { ### Algorithm 3: Banking System with Methods -```java +``` import java.util.Scanner; public class BankingSystem { - + public static void displayBankMenu() { System.out.println("\n=== Banking System ==="); System.out.println("1. Deposit"); @@ -938,7 +938,7 @@ public class BankingSystem { System.out.println("5. Exit"); System.out.print("Choose option (1-5): "); } - + public static double deposit(double balance, double amount) { if (amount > 0) { double newBalance = balance + amount; @@ -950,7 +950,7 @@ public class BankingSystem { return balance; } } - + public static double withdraw(double balance, double amount) { if (amount > 0 && amount <= balance) { double newBalance = balance - amount; @@ -965,11 +965,11 @@ public class BankingSystem { return balance; } } - + public static void displayBalance(double balance) { System.out.printf(" Current Balance: $%.2f\n", balance); } - + public static int addTransaction(String[] transactions, int count, String type, double amount) { if (count < 100) { transactions[count] = String.format("%s $%.2f", type, amount); @@ -978,7 +978,7 @@ public class BankingSystem { return count; } } - + public static void displayTransactions(String[] transactions, int count) { if (count > 0) { System.out.println("\n=== Transaction History ==="); @@ -989,18 +989,18 @@ public class BankingSystem { System.out.println("ℹ No transactions yet."); } } - + public static void main(String[] args) { Scanner scanner = new Scanner(System.in); double balance = 1000.00; String[] transactions = new String[100]; int transactionCount = 0; boolean running = true; - + while (running) { displayBankMenu(); int choice = scanner.nextInt(); - + switch (choice) { case 1: System.out.print("Enter deposit amount: $"); @@ -1008,7 +1008,7 @@ public class BankingSystem { double oldBalance = balance; balance = deposit(balance, depositAmount); if (balance != oldBalance) { - transactionCount = addTransaction(transactions, transactionCount, + transactionCount = addTransaction(transactions, transactionCount, "Deposit", depositAmount); } break; @@ -1018,7 +1018,7 @@ public class BankingSystem { oldBalance = balance; balance = withdraw(balance, withdrawAmount); if (balance != oldBalance) { - transactionCount = addTransaction(transactions, transactionCount, + transactionCount = addTransaction(transactions, transactionCount, "Withdrawal", withdrawAmount); } break; @@ -1036,12 +1036,12 @@ public class BankingSystem { break; } } - + System.out.println("Thank you for banking with us! "); scanner.close(); } } -```java +``` **Key Concepts:** - Methods returning new balance (double) @@ -1063,12 +1063,12 @@ public class BankingSystem { ### Algorithm 4: Statistics Calculator with Methods -```java +``` import java.util.Scanner; import java.util.Arrays; public class StatisticsCalculator { - + public static void displayStatsMenu() { System.out.println("\n=== Statistics Calculator ==="); System.out.println("1. Enter Data"); @@ -1079,11 +1079,11 @@ public class StatisticsCalculator { System.out.println("6. Exit"); System.out.print("Choose option (1-6): "); } - + public static int enterData(double[] data, Scanner scanner) { System.out.print("How many numbers to enter? "); int count = scanner.nextInt(); - + if (count > 0 && count <= 100) { for (int i = 0; i < count; i++) { System.out.print("Enter number " + (i + 1) + ": "); @@ -1096,7 +1096,7 @@ public class StatisticsCalculator { return 0; } } - + public static double calculateMean(double[] data, int count) { if (count > 0) { double sum = 0; @@ -1108,13 +1108,13 @@ public class StatisticsCalculator { return 0; } } - + public static double calculateMedian(double[] data, int count) { if (count > 0) { // Create copy to avoid modifying original double[] sorted = Arrays.copyOf(data, count); Arrays.sort(sorted); - + if (count % 2 == 1) { return sorted[count / 2]; } else { @@ -1126,12 +1126,12 @@ public class StatisticsCalculator { return 0; } } - + public static double calculateMode(double[] data, int count) { if (count > 0) { int maxFrequency = 0; double mode = data[0]; - + for (int i = 0; i < count; i++) { int frequency = 0; for (int j = 0; j < count; j++) { @@ -1139,19 +1139,19 @@ public class StatisticsCalculator { frequency++; } } - + if (frequency > maxFrequency) { maxFrequency = frequency; mode = data[i]; } } - + return mode; } else { return 0; } } - + public static void displayAllStats(double[] data, int count) { if (count > 0) { System.out.println("\n=== Statistical Summary ==="); @@ -1163,17 +1163,17 @@ public class StatisticsCalculator { System.out.println("ℹ No data entered yet."); } } - + public static void main(String[] args) { Scanner scanner = new Scanner(System.in); double[] data = new double[100]; int dataCount = 0; boolean running = true; - + while (running) { displayStatsMenu(); int choice = scanner.nextInt(); - + switch (choice) { case 1: dataCount = enterData(data, scanner); @@ -1210,12 +1210,12 @@ public class StatisticsCalculator { break; } } - + System.out.println("Thank you for using Statistics Calculator! "); scanner.close(); } } -```java +``` **Key Concepts:** - Statistical calculation methods @@ -1237,11 +1237,11 @@ public class StatisticsCalculator { ### Algorithm 5: Text Analyzer with Methods -```java +``` import java.util.Scanner; public class TextAnalyzer { - + public static void displayTextMenu() { System.out.println("\n=== Text Analyzer ==="); System.out.println("1. Enter Text"); @@ -1253,7 +1253,7 @@ public class TextAnalyzer { System.out.println("7. Exit"); System.out.print("Choose option (1-7): "); } - + public static String enterText(Scanner scanner) { scanner.nextLine(); // Consume newline System.out.print("Enter text: "); @@ -1261,12 +1261,12 @@ public class TextAnalyzer { System.out.println(" Text entered successfully!"); return text; } - + public static int countWords(String text) { if (text.isEmpty()) { return 0; } - + int count = 1; for (int i = 0; i < text.length(); i++) { if (text.charAt(i) == ' ') { @@ -1275,15 +1275,15 @@ public class TextAnalyzer { } return count; } - + public static int countCharacters(String text) { return text.length(); } - + public static int countVowels(String text) { int count = 0; String vowels = "aeiouAEIOU"; - + for (int i = 0; i < text.length(); i++) { char c = text.charAt(i); if (vowels.indexOf(c) != -1) { @@ -1292,7 +1292,7 @@ public class TextAnalyzer { } return count; } - + public static String reverseText(String text) { StringBuilder reversed = new StringBuilder(); for (int i = text.length() - 1; i >= 0; i--) { @@ -1300,7 +1300,7 @@ public class TextAnalyzer { } return reversed.toString(); } - + public static void displayAllAnalysis(String text) { if (!text.isEmpty()) { System.out.println("\n=== Text Analysis Results ==="); @@ -1313,16 +1313,16 @@ public class TextAnalyzer { System.out.println("ℹ No text entered yet."); } } - + public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String text = ""; boolean running = true; - + while (running) { displayTextMenu(); int choice = scanner.nextInt(); - + switch (choice) { case 1: text = enterText(scanner); @@ -1366,12 +1366,12 @@ public class TextAnalyzer { break; } } - + System.out.println("Thank you for using Text Analyzer! "); scanner.close(); } } -```java +``` **Key Concepts:** - String manipulation methods @@ -1400,7 +1400,7 @@ public class TextAnalyzer { ### Method Design Patterns in Java **Input Validation Method:** -```java +``` public static int getValidInt(Scanner scanner, String prompt, int min, int max) { while (true) { System.out.print(prompt); @@ -1415,10 +1415,10 @@ public static int getValidInt(Scanner scanner, String prompt, int min, int max) System.out.printf("Please enter a number between %d and %d\n", min, max); } } -```java +``` **Array Processing Pattern:** -```java +``` public static double processArray(double[] array, int count) { double result = 0; for (int i = 0; i < count; i++) { @@ -1431,10 +1431,10 @@ private static double someOperation(double value) { // Helper method for complex operation return value * 2; } -```java +``` **Menu-Driven Pattern:** -```java +``` public static void displayMenu() { System.out.println("\n=== Menu ==="); // Display options @@ -1451,10 +1451,10 @@ public static void handleChoice(int choice, /* parameters */) { // etc. } } -```java +``` --- - **Congratulations! You've mastered method-based programming in Java!** + **Congratulations! You've mastered method-based programming in Java!** *You've completed Stage 2! You can now translate pseudocode into well-organized, modular Java programs. Next stages will challenge you with problem-solving and algorithm design! * diff --git a/lessons/java/stage-3/level-1/lesson.md b/lessons/java/stage-3/level-1/lesson.md index 33fa1a3..fd5435c 100644 --- a/lessons/java/stage-3/level-1/lesson.md +++ b/lessons/java/stage-3/level-1/lesson.md @@ -51,19 +51,19 @@ Simple Problem Analysis - Design an algorithm to solve this problem, then implem ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` javac hello.java ``` 2. **Run your program**: - ```bash + ``` java hello ``` **Expected output:** -```java +``` Hello, World! -```java +``` ### How to Approach This @@ -160,7 +160,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```java +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -174,7 +174,7 @@ BEGIN - Step 3 4. Display results END -```java +``` Then translate this directly to Java code. diff --git a/lessons/java/stage-3/level-2/lesson.md b/lessons/java/stage-3/level-2/lesson.md index db04c73..453f9c0 100644 --- a/lessons/java/stage-3/level-2/lesson.md +++ b/lessons/java/stage-3/level-2/lesson.md @@ -51,19 +51,19 @@ Data Structure Planning - Design an algorithm to solve this problem, then implem ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` javac hello.java ``` 2. **Run your program**: - ```bash + ``` java hello ``` **Expected output:** -```java +``` Hello, World! -```java +``` ### How to Approach This @@ -160,7 +160,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```java +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -174,7 +174,7 @@ BEGIN - Step 3 4. Display results END -```java +``` Then translate this directly to Java code. diff --git a/lessons/java/stage-3/level-3/lesson.md b/lessons/java/stage-3/level-3/lesson.md index b2d4d52..2e4d96c 100644 --- a/lessons/java/stage-3/level-3/lesson.md +++ b/lessons/java/stage-3/level-3/lesson.md @@ -51,19 +51,19 @@ Mathematical Problems - Design an algorithm to solve this problem, then implemen ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` javac hello.java ``` 2. **Run your program**: - ```bash + ``` java hello ``` **Expected output:** -```java +``` Hello, World! -```java +``` ### How to Approach This @@ -160,7 +160,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```java +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -174,7 +174,7 @@ BEGIN - Step 3 4. Display results END -```java +``` Then translate this directly to Java code. diff --git a/lessons/java/stage-3/level-4/lesson.md b/lessons/java/stage-3/level-4/lesson.md index 6c2cecd..8403045 100644 --- a/lessons/java/stage-3/level-4/lesson.md +++ b/lessons/java/stage-3/level-4/lesson.md @@ -51,19 +51,19 @@ Text Processing Problems - Design an algorithm to solve this problem, then imple ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` javac hello.java ``` 2. **Run your program**: - ```bash + ``` java hello ``` **Expected output:** -```java +``` Hello, World! -```java +``` ### How to Approach This @@ -160,7 +160,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```java +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -174,7 +174,7 @@ BEGIN - Step 3 4. Display results END -```java +``` Then translate this directly to Java code. diff --git a/lessons/java/stage-3/level-5/lesson.md b/lessons/java/stage-3/level-5/lesson.md index cb5908c..7110453 100644 --- a/lessons/java/stage-3/level-5/lesson.md +++ b/lessons/java/stage-3/level-5/lesson.md @@ -51,19 +51,19 @@ Logic Problems - Design an algorithm to solve this problem, then implement it. ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` javac hello.java ``` 2. **Run your program**: - ```bash + ``` java hello ``` **Expected output:** -```java +``` Hello, World! -```java +``` ### How to Approach This @@ -160,7 +160,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```java +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -174,7 +174,7 @@ BEGIN - Step 3 4. Display results END -```java +``` Then translate this directly to Java code. diff --git a/lessons/java/stage-3/level-6/lesson.md b/lessons/java/stage-3/level-6/lesson.md index cdd3e66..a8c556c 100644 --- a/lessons/java/stage-3/level-6/lesson.md +++ b/lessons/java/stage-3/level-6/lesson.md @@ -51,19 +51,19 @@ Search Algorithms - Design an algorithm to solve this problem, then implement it ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` javac hello.java ``` 2. **Run your program**: - ```bash + ``` java hello ``` **Expected output:** -```java +``` Hello, World! -```java +``` ### How to Approach This @@ -160,7 +160,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```java +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -174,7 +174,7 @@ BEGIN - Step 3 4. Display results END -```java +``` Then translate this directly to Java code. diff --git a/lessons/java/stage-3/level-7/lesson.md b/lessons/java/stage-3/level-7/lesson.md index 7dea073..b385c6c 100644 --- a/lessons/java/stage-3/level-7/lesson.md +++ b/lessons/java/stage-3/level-7/lesson.md @@ -51,19 +51,19 @@ Sorting Algorithms - Design an algorithm to solve this problem, then implement i ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` javac hello.java ``` 2. **Run your program**: - ```bash + ``` java hello ``` **Expected output:** -```java +``` Hello, World! -```java +``` ### How to Approach This @@ -160,7 +160,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```java +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -174,7 +174,7 @@ BEGIN - Step 3 4. Display results END -```java +``` Then translate this directly to Java code. diff --git a/lessons/java/stage-4/level-1/lesson.md b/lessons/java/stage-4/level-1/lesson.md index f8f877a..12c31f6 100644 --- a/lessons/java/stage-4/level-1/lesson.md +++ b/lessons/java/stage-4/level-1/lesson.md @@ -51,19 +51,19 @@ Build a complete Calculator Application application that: ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` javac hello.java ``` 2. **Run your program**: - ```bash + ``` java hello ``` **Expected output:** -```java +``` Hello, World! -```java +``` ### How to Approach This @@ -163,13 +163,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```java +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```java +``` Build incrementally - get one feature working before adding the next. diff --git a/lessons/java/stage-4/level-2/lesson.md b/lessons/java/stage-4/level-2/lesson.md index e322d02..57c4b57 100644 --- a/lessons/java/stage-4/level-2/lesson.md +++ b/lessons/java/stage-4/level-2/lesson.md @@ -51,19 +51,19 @@ Build a complete Text Analysis Tool application that: ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` javac hello.java ``` 2. **Run your program**: - ```bash + ``` java hello ``` **Expected output:** -```java +``` Hello, World! -```java +``` ### How to Approach This @@ -163,13 +163,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```java +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```java +``` Build incrementally - get one feature working before adding the next. diff --git a/lessons/java/stage-4/level-3/lesson.md b/lessons/java/stage-4/level-3/lesson.md index b21479d..7737429 100644 --- a/lessons/java/stage-4/level-3/lesson.md +++ b/lessons/java/stage-4/level-3/lesson.md @@ -51,19 +51,19 @@ Build a complete Data Processing application that: ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` javac hello.java ``` 2. **Run your program**: - ```bash + ``` java hello ``` **Expected output:** -```java +``` Hello, World! -```java +``` ### How to Approach This @@ -163,13 +163,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```java +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```java +``` Build incrementally - get one feature working before adding the next. diff --git a/lessons/java/stage-4/level-4/lesson.md b/lessons/java/stage-4/level-4/lesson.md index ed7ef85..4f059ad 100644 --- a/lessons/java/stage-4/level-4/lesson.md +++ b/lessons/java/stage-4/level-4/lesson.md @@ -51,19 +51,19 @@ Build a complete File Operations application that: ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` javac hello.java ``` 2. **Run your program**: - ```bash + ``` java hello ``` **Expected output:** -```java +``` Hello, World! -```java +``` ### How to Approach This @@ -163,13 +163,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```java +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```java +``` Build incrementally - get one feature working before adding the next. diff --git a/lessons/java/stage-4/level-5/lesson.md b/lessons/java/stage-4/level-5/lesson.md index ce6e8fc..39b87c9 100644 --- a/lessons/java/stage-4/level-5/lesson.md +++ b/lessons/java/stage-4/level-5/lesson.md @@ -51,19 +51,19 @@ Build a complete API Integration application that: ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` javac hello.java ``` 2. **Run your program**: - ```bash + ``` java hello ``` **Expected output:** -```java +``` Hello, World! -```java +``` ### How to Approach This @@ -163,13 +163,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```java +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```java +``` Build incrementally - get one feature working before adding the next. diff --git a/lessons/java/stage-4/level-6/lesson.md b/lessons/java/stage-4/level-6/lesson.md index 27cbd7d..8f69827 100644 --- a/lessons/java/stage-4/level-6/lesson.md +++ b/lessons/java/stage-4/level-6/lesson.md @@ -51,19 +51,19 @@ Build a complete Database Operations application that: ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` javac hello.java ``` 2. **Run your program**: - ```bash + ``` java hello ``` **Expected output:** -```java +``` Hello, World! -```java +``` ### How to Approach This @@ -163,13 +163,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```java +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```java +``` Build incrementally - get one feature working before adding the next. diff --git a/lessons/java/stage-4/level-7/lesson.md b/lessons/java/stage-4/level-7/lesson.md index cd2a8fb..9e3843c 100644 --- a/lessons/java/stage-4/level-7/lesson.md +++ b/lessons/java/stage-4/level-7/lesson.md @@ -51,19 +51,19 @@ Build a complete Complete Application application that: ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` javac hello.java ``` 2. **Run your program**: - ```bash + ``` java hello ``` **Expected output:** -```java +``` Hello, World! -```java +``` ### How to Approach This @@ -163,13 +163,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```java +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```java +``` Build incrementally - get one feature working before adding the next. diff --git a/lessons/java/stage-5/level-1/lesson.md b/lessons/java/stage-5/level-1/lesson.md index abfe457..4638619 100644 --- a/lessons/java/stage-5/level-1/lesson.md +++ b/lessons/java/stage-5/level-1/lesson.md @@ -242,14 +242,14 @@ Follow these stages: **Your architecture will depend on your chosen project, but should include:** -```java +``` // Main program structure // - Data definitions // - Core functions // - User interface // - File operations // - Main program loop -```java +``` **Recommended Organization:** 1. Separate data structures from logic diff --git a/lessons/java/stage-5/level-2/lesson.md b/lessons/java/stage-5/level-2/lesson.md index 45ba228..de9043f 100644 --- a/lessons/java/stage-5/level-2/lesson.md +++ b/lessons/java/stage-5/level-2/lesson.md @@ -233,14 +233,14 @@ Follow these stages: **Your architecture will depend on your chosen project, but should include:** -```java +``` // Main program structure // - Data definitions // - Core functions // - User interface // - File operations // - Main program loop -```java +``` **Recommended Organization:** 1. Separate data structures from logic diff --git a/lessons/java/stage-5/level-3/lesson.md b/lessons/java/stage-5/level-3/lesson.md index 397b5dd..b8ada2a 100644 --- a/lessons/java/stage-5/level-3/lesson.md +++ b/lessons/java/stage-5/level-3/lesson.md @@ -238,14 +238,14 @@ Follow these stages: **Your architecture will depend on your chosen project, but should include:** -```java +``` // Main program structure // - Data definitions // - Core functions // - User interface // - File operations // - Main program loop -```java +``` **Recommended Organization:** 1. Separate data structures from logic diff --git a/lessons/java/stage-5/level-4/lesson.md b/lessons/java/stage-5/level-4/lesson.md index b0cf23d..1b098e7 100644 --- a/lessons/java/stage-5/level-4/lesson.md +++ b/lessons/java/stage-5/level-4/lesson.md @@ -233,14 +233,14 @@ Follow these stages: **Your architecture will depend on your chosen project, but should include:** -```java +``` // Main program structure // - Data definitions // - Core functions // - User interface // - File operations // - Main program loop -```java +``` **Recommended Organization:** 1. Separate data structures from logic diff --git a/lessons/java/stage-5/level-5/lesson.md b/lessons/java/stage-5/level-5/lesson.md index 9408bfc..5623394 100644 --- a/lessons/java/stage-5/level-5/lesson.md +++ b/lessons/java/stage-5/level-5/lesson.md @@ -238,14 +238,14 @@ Follow these stages: **Your architecture will depend on your chosen project, but should include:** -```java +``` // Main program structure // - Data definitions // - Core functions // - User interface // - File operations // - Main program loop -```java +``` **Recommended Organization:** 1. Separate data structures from logic diff --git a/lessons/java/stage-5/level-6/lesson.md b/lessons/java/stage-5/level-6/lesson.md index 58cac36..4cac409 100644 --- a/lessons/java/stage-5/level-6/lesson.md +++ b/lessons/java/stage-5/level-6/lesson.md @@ -232,14 +232,14 @@ Follow these stages: **Your architecture will depend on your chosen project, but should include:** -```java +``` // Main program structure // - Data definitions // - Core functions // - User interface // - File operations // - Main program loop -```java +``` **Recommended Organization:** 1. Separate data structures from logic diff --git a/lessons/java/stage-5/level-7/lesson.md b/lessons/java/stage-5/level-7/lesson.md index 2bc16d3..c85d6b1 100644 --- a/lessons/java/stage-5/level-7/lesson.md +++ b/lessons/java/stage-5/level-7/lesson.md @@ -235,14 +235,14 @@ Follow these stages: **Your architecture will depend on your chosen project, but should include:** -```java +``` // Main program structure // - Data definitions // - Core functions // - User interface // - File operations // - Main program loop -```java +``` **Recommended Organization:** 1. Separate data structures from logic diff --git a/lessons/javascript/stage-1/level-1/lesson.md b/lessons/javascript/stage-1/level-1/lesson.md index 3586d22..8f1221b 100644 --- a/lessons/javascript/stage-1/level-1/lesson.md +++ b/lessons/javascript/stage-1/level-1/lesson.md @@ -25,9 +25,9 @@ Welcome to your first step into JavaScript programming! Today, you'll learn how **Copy the following code EXACTLY as shown below into a new file called `hello.js`** -```javascript +``` console.log("Hello, World!"); -```javascript +``` --- @@ -35,18 +35,18 @@ console.log("Hello, World!"); 1. **Open your terminal** (or command prompt) 2. **Navigate to where you saved your file**: - ```bash + ``` cd /path/to/your/folder - ```java + ``` 3. **Run your program**: - ```bash + ``` node hello.js - ```bash + ``` **Expected output:** -```javascript +``` Hello, World! -```javascript +``` --- @@ -97,9 +97,9 @@ Remember to check the `VIM_CHEATSHEET.md` in the root directory for basic Vim co ### Code Breakdown -```javascript +``` console.log("Hello, World!"); -```javascript +``` - **`console`** = Built-in object that provides access to the browser's debugging console (or Node.js terminal) - **`.`** = Property accessor - accesses the log function inside console object - **`log`** = Method (function) that prints messages to the console @@ -142,7 +142,7 @@ Today's lesson uses Node.js, which allows us to run JavaScript outside the brows --- - **Congratulations! You've written your first JavaScript program!** + **Congratulations! You've written your first JavaScript program!** *Keep moving forward - next up: Variables!* @@ -169,40 +169,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```js -console.log("Hello, World!"); - -```js - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard javascript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/javascript/stage-1/level-2/lesson.md b/lessons/javascript/stage-1/level-2/lesson.md index c394fee..4be8254 100644 --- a/lessons/javascript/stage-1/level-2/lesson.md +++ b/lessons/javascript/stage-1/level-2/lesson.md @@ -25,7 +25,7 @@ Welcome to the world of variables! Today you'll learn how to store and use data **Copy the following code into a new file called `variables.js`** -```javascript +``` // String variables (text) let name = "Alex"; let city = "New York"; @@ -68,19 +68,19 @@ dynamicVar = 42; // Now it's a number! console.log("Dynamic variable: " + dynamicVar); dynamicVar = true; // Now it's a boolean! console.log("Dynamic variable: " + dynamicVar); -```javascript +``` --- ### How to Execute 1. **Run your program**: - ```bash + ``` node variables.js - ```java + ``` **Expected output:** -```javascript +``` === Personal Info === Name: Alex City: New York @@ -100,7 +100,7 @@ Happy: true Dynamic variable: I'm a string Dynamic variable: 42 Dynamic variable: true -```javascript +``` --- @@ -154,10 +154,10 @@ JavaScript has several important concepts about variables: ### Code Breakdown -```javascript +``` // String variables (text) let name = "Alex"; -```javascript +``` - **`//`** = Single-line comment (ignored by computer) - **`let`** = Keyword to declare a variable that can be reassigned - **`name`** = Variable name (follows naming rules) @@ -165,22 +165,22 @@ let name = "Alex"; - **`"Alex"`** = String value (text in quotes) - **`;`** = End of statement -```javascript +``` let age = 25; -```javascript +``` - **`age`** = Variable name (numeric variable) - **`25`** = Number value (no quotes needed for numbers) - JavaScript treats integers and decimals the same way -```javascript +``` let isStudent = true; -```javascript +``` - **`isStudent`** = Boolean variable name (descriptive naming) - **`true`** = Boolean value (one of only two possible values: true or false) -```javascript +``` console.log("Name: " + name); -```javascript +``` - **`+`** = String concatenation operator (joins strings together) - The variable `name` gets its value inserted into the output string @@ -192,7 +192,7 @@ JavaScript has three main ways to declare variables: 2. **`let`** - Modern way for variables that change 3. **`const`** - For variables that won't change -```javascript +``` // var (old style - avoid) var oldStyle = "Don't use this much anymore"; @@ -201,7 +201,7 @@ let canChange = "This value can be updated later"; // const (modern - for constants that won't change) const neverChanges = "This value cannot be changed"; -```javascript +``` ### Variable Naming Rules @@ -231,7 +231,7 @@ const neverChanges = "This value cannot be changed"; JavaScript is dynamically typed, meaning: -```javascript +``` let dynamic = "I start as a string"; console.log(typeof dynamic); // Output: "string" @@ -240,7 +240,7 @@ console.log(typeof dynamic); // Output: "number" dynamic = true; // Now it's a boolean console.log(typeof dynamic); // Output: "boolean" -```javascript +``` This is different from statically typed languages like C/C++ where you must declare the type in advance. @@ -248,7 +248,7 @@ This is different from statically typed languages like C/C++ where you must decl There are multiple ways to combine strings: -```javascript +``` let firstName = "John"; let lastName = "Doe"; @@ -260,7 +260,7 @@ console.log(`Full name: ${firstName} ${lastName}`); // Method 3: concat() method console.log("Full name: ".concat(firstName, " ", lastName)); -```javascript +``` ### Common Errors & Solutions @@ -282,7 +282,7 @@ console.log("Full name: ".concat(firstName, " ", lastName)); Try this modified version: -```javascript +``` // Let's do some calculations with variables! const currentYear = 2025; let birthYear = 2000; @@ -301,11 +301,11 @@ console.log("Full name: " + fullName); // JavaScript's type conversion console.log("Number and string: " + (5 + "3")); // Output: "53" console.log("Number math: " + (5 + 3)); // Output: "8" -```javascript +``` --- - **Excellent work! You now understand variables - the foundation of all programming!** + **Excellent work! You now understand variables - the foundation of all programming!** *Ready for the next challenge? Let's do some math with our variables!* @@ -332,40 +332,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```js -console.log("Hello, World!"); - -```js - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard javascript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/javascript/stage-1/level-3/lesson.md b/lessons/javascript/stage-1/level-3/lesson.md index dc6d3c0..54d8050 100644 --- a/lessons/javascript/stage-1/level-3/lesson.md +++ b/lessons/javascript/stage-1/level-3/lesson.md @@ -25,7 +25,7 @@ Time to do some math! Today you'll learn how to perform mathematical operations **Copy the following code into a new file called `math.js`** -```javascript +``` // Basic arithmetic operations console.log("=== Basic Arithmetic ==="); @@ -116,19 +116,19 @@ console.log("After *= 2: " + value); value /= 4; // Same as: value = value / 4 console.log("After /= 4: " + value); -```javascript +``` --- ### How to Execute 1. **Run your program**: - ```bash + ``` node math.js - ```java + ``` **Expected output:** -```javascript +``` === Basic Arithmetic === 5 + 3 = 8 10 - 4 = 6 @@ -160,7 +160,7 @@ After += 5: 15 After -= 3: 12 After *= 2: 24 After /= 4: 6 -```javascript +``` --- @@ -221,26 +221,26 @@ In JavaScript math, you saw some operators: ### Code Breakdown -```javascript +``` let sum = 5 + 3; console.log("5 + 3 = " + sum); -```javascript +``` - **`=`** = Assignment operator (stores the result of 5 + 3 into variable 'sum') - **`+`** = Addition operator (performs arithmetic addition) - **String concatenation**: The `+` operator also joins strings when one operand is a string -```javascript +``` let remainder = 17 % 5; console.log("17 % 5 = " + remainder + " (remainder)"); -```javascript +``` - **`%`** = Modulo operator (returns the remainder after division) - 17 ÷ 5 = 3 remainder 2, so 17 % 5 = 2 - Useful for checking if numbers are even (n % 2 === 0) or cycling through values -```javascript +``` let power = 2 ** 3; console.log("2 ** 3 = " + power + " (2 to the power of 3)"); -```javascript +``` - **`**`** = Exponentiation operator (new in ES2016) - 2 ** 3 = 2 to the power of 3 = 2 × 2 × 2 = 8 - Alternative to Math.pow(2, 3) @@ -255,19 +255,19 @@ JavaScript follows the standard mathematical order of operations: 4. **A**ddition `+` and **S**ubtraction `-` (left to right) Examples: -```javascript +``` // Without parentheses: Multiplication before addition 10 + 5 * 2; // = 10 + 10 = 20 (not 30!) // With parentheses: Addition before multiplication (10 + 5) * 2; // = 15 * 2 = 30 -```javascript +``` ### Increment/Decrement Operators JavaScript has special operators for adding/subtracting 1: -```javascript +``` let x = 5; // Pre-increment (++x): Add 1 FIRST, then return the new value @@ -277,13 +277,13 @@ console.log(++x); // Prints: 6 (x is now 6) let y = 5; console.log(y++); // Prints: 5 (y is now 6) console.log(y); // Prints: 6 -```javascript +``` ### Compound Assignment Operators These combine an operation with assignment: -```javascript +``` let value = 10; value += 5; // Same as: value = value + 5; // value is now 15 @@ -291,26 +291,26 @@ value -= 3; // Same as: value = value - 3; // value is now 12 value *= 2; // Same as: value = value * 2; // value is now 24 value /= 4; // Same as: value = value / 4; // value is now 6 value %= 3; // Same as: value = value % 3; // value is now 0 -```javascript +``` ### Important JavaScript Math Notes **Floating Point Precision:** -```javascript +``` console.log(0.1 + 0.2); // Output: 0.30000000000000004 (not exactly 0.3!) -```javascript +``` This is due to how JavaScript (and most programming languages) store decimal numbers internally. **Division by Zero:** -```javascript +``` console.log(5 / 0); // Output: Infinity console.log(-5 / 0); // Output: -Infinity console.log(0 / 0); // Output: NaN (Not a Number) -```javascript +``` **Mathematical Functions:** For more complex math, JavaScript has a built-in Math object: -```javascript +``` Math.sqrt(16); // Square root: 4 Math.max(1, 5, 3); // Maximum: 5 Math.min(1, 5, 3); // Minimum: 1 @@ -318,7 +318,7 @@ Math.round(4.7); // Round: 5 Math.floor(4.7); // Floor: 4 Math.ceil(4.2); // Ceiling: 5 Math.PI; // Pi: 3.141592653589793 -```javascript +``` ### Common Errors & Solutions @@ -342,7 +342,7 @@ JavaScript math is used everywhere: Try this complex calculation: -```javascript +``` // Compound interest calculation let principal = 1000; // Initial amount let rate = 0.05; // 5% annual interest rate @@ -360,11 +360,11 @@ let original = 100; let newAmount = 125; let percentageChange = ((newAmount - original) / original) * 100; console.log("Percentage change from " + original + " to " + newAmount + ": " + percentageChange + "%"); -```javascript +``` --- - **Excellent work! You're becoming a mathematical wizard in JavaScript!** + **Excellent work! You're becoming a mathematical wizard in JavaScript!** *Ready for the next challenge? Let's learn how to get input from users!* @@ -391,40 +391,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```js -console.log("Hello, World!"); - -```js - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard javascript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/javascript/stage-1/level-4/lesson.md b/lessons/javascript/stage-1/level-4/lesson.md index 381b03d..3fe00b6 100644 --- a/lessons/javascript/stage-1/level-4/lesson.md +++ b/lessons/javascript/stage-1/level-4/lesson.md @@ -25,13 +25,13 @@ Now let's make our programs interactive! Today you'll learn how to get input fro **First, install the readline-sync module (if not already installed):** -```bash +``` npm install readline-sync -```javascript +``` **Then copy the following code into a new file called `input.js`** -```javascript +``` // Import the readline-sync module for user input const readlineSync = require('readline-sync'); @@ -97,11 +97,11 @@ if (index > -1) { } else { console.log("You didn't select anything!"); } -```javascript +``` **Note:** If you don't want to install readline-sync, you can create a simpler version that demonstrates the concept without user interaction by replacing the input with preset values. Create an alternate version in `simple_input.js`: -```javascript +``` // This is a simplified version that doesn't require user input // We'll simulate user answers with predefined values @@ -151,7 +151,7 @@ if (answer.toLowerCase() === "paris") { } else { console.log("Not quite! The answer is Paris."); } -```javascript +``` --- @@ -159,19 +159,19 @@ if (answer.toLowerCase() === "paris") { **For the full interactive version:** 1. **Install readline-sync** (if not already installed): - ```bash + ``` npm install readline-sync - ```java + ``` 2. **Run your program**: - ```bash + ``` node input.js - ```java + ``` **For the simplified version (no installation needed):** 1. **Run your program**: - ```bash + ``` node simple_input.js - ```java + ``` --- @@ -227,24 +227,24 @@ if (answer.toLowerCase() === "paris") { ### Code Breakdown -```javascript +``` const readlineSync = require('readline-sync'); -```javascript +``` - **`const`** = Declares a constant (value that won't change) - **`require()`** = Imports external module functionality - **`'readline-sync'`** = The module name we want to import - This module allows us to get user input synchronously (waits for input before continuing) -```javascript +``` let name = readlineSync.question("What's your name? "); -```javascript +``` - **`readlineSync.question()`** = Method to get text input from user - **`"What's your name? "`** = Prompt message shown to user - **Returns a string** containing whatever the user typed -```javascript +``` let num1 = parseFloat(readlineSync.question("Enter first number: ")); -```javascript +``` - **`parseFloat()`** = Converts string to floating-point number - **Necessary** because `readlineSync.question()` returns a string, but we want to do math - **`parseInt()`** = For integers (whole numbers only) @@ -253,7 +253,7 @@ let num1 = parseFloat(readlineSync.question("Enter first number: ")); ### Alternative Input Methods **In Browser Environment (HTML):** -```html +``` @@ -263,20 +263,20 @@ let num1 = parseFloat(readlineSync.question("Enter first number: ")); -```javascript +``` **Command Line Arguments:** -```javascript +``` // Access arguments passed to node: `node program.js arg1 arg2` let name = process.argv[2]; // First argument after filename console.log("Hello, " + name + "!"); -```javascript +``` ### Data Type Conversion JavaScript is dynamically typed, but we still need to convert strings to numbers for math: -```javascript +``` // Without conversion - concatenation instead of addition! let str1 = "5"; let str2 = "3"; @@ -286,13 +286,13 @@ console.log(str1 + str2); // Output: "53" (not 8!) let num1 = parseFloat("5"); let num2 = parseFloat("3"); console.log(num1 + num2); // Output: 8 -```javascript +``` ### Error Handling for Input Real programs need to handle invalid input: -```javascript +``` let userInput = readlineSync.question("Enter a number: "); let number = parseFloat(userInput); @@ -301,21 +301,21 @@ if (isNaN(number)) { // Check if it's Not-a-Number } else { console.log("You entered: " + number); } -```javascript +``` ### readline-sync Methods **Text Input:** -```javascript +``` // Get any text let name = readlineSync.question("Name: "); // Get text with masking (good for passwords) let password = readlineSync.question("Password: ", {hideEchoBack: true}); -```javascript +``` **Yes/No Questions:** -```javascript +``` // Returns true for yes/y/Y, false for no/n/N let continue = readlineSync.keyInYN("Continue? "); if (continue) { @@ -323,21 +323,21 @@ if (continue) { } else { console.log("Exiting..."); } -```javascript +``` **Multiple Choice:** -```javascript +``` let colors = ['Red', 'Blue', 'Green']; let index = readlineSync.keyInSelect(colors, 'Choose a color: '); if (index > -1) { // -1 means no selection console.log("You chose: " + colors[index]); } -```javascript +``` ### Date and Time in JavaScript -```javascript +``` // Get current date and time let now = new Date(); console.log(now); // Full date/time @@ -346,7 +346,7 @@ console.log(now); // Full date/time let currentYear = now.getFullYear(); // 2025 (or current year) let currentMonth = now.getMonth() + 1; // 0-11, so add 1 for 1-12 let currentDay = now.getDate(); // 1-31 -```javascript +``` ### Common Errors & Solutions @@ -361,7 +361,7 @@ let currentDay = now.getDate(); // 1-31 ### Best Practices for Input **Always validate user input:** -```javascript +``` let userInput = readlineSync.question("Enter age: "); let age = parseInt(userInput); @@ -371,15 +371,15 @@ if (isNaN(age) || age < 0 || age > 150) { } else { console.log("You are " + age + " years old"); } -```javascript +``` **Handle different string cases:** -```javascript +``` let answer = readlineSync.question("Yes or No? "); if (answer.toLowerCase() === "yes" || answer.toLowerCase() === "y") { console.log("You said yes!"); } -```javascript +``` ### Security Considerations @@ -392,7 +392,7 @@ When accepting user input, be aware of potential security issues: Try this full interactive program: -```javascript +``` const readlineSync = require('readline-sync'); console.log("=== Personal Finance Calculator ==="); @@ -424,11 +424,11 @@ if (remaining > 0) { } else { console.log("You're spending more than you earn. Consider reducing expenses."); } -```javascript +``` --- - **Excellent work! You now know how to make interactive programs that respond to user input!** + **Excellent work! You now know how to make interactive programs that respond to user input!** *Ready for the next challenge? Let's make programs that make decisions!* @@ -455,40 +455,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```js -console.log("Hello, World!"); - -```js - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard javascript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/javascript/stage-1/level-5/lesson.md b/lessons/javascript/stage-1/level-5/lesson.md index 5695bd0..4879885 100644 --- a/lessons/javascript/stage-1/level-5/lesson.md +++ b/lessons/javascript/stage-1/level-5/lesson.md @@ -25,7 +25,7 @@ Time to make programs that can make decisions! Today you'll learn how to write c **Copy the following code into a new file called `conditionals.js`** -```javascript +``` console.log("=== Simple Age Check ==="); // Input for age let age = 20; @@ -171,23 +171,23 @@ console.log("Score: " + score + ", Result: " + result); // Ternary with multiple conditions let timeOfDay = 14; // 24-hour format -let greeting = timeOfDay < 12 ? "Good morning!" : - timeOfDay < 18 ? "Good afternoon!" : +let greeting = timeOfDay < 12 ? "Good morning!" : + timeOfDay < 18 ? "Good afternoon!" : "Good evening!"; console.log("Time: " + timeOfDay + ":00, Greeting: " + greeting); -```javascript +``` --- ### How to Execute 1. **Run your program**: - ```bash + ``` node conditionals.js - ```java + ``` **Expected output:** -```javascript +``` === Simple Age Check === You are an adult (18 or older) @@ -217,7 +217,7 @@ Today is Wednesday - middle of the week === Ternary Operator Demo === Score: 88, Result: Pass Time: 14:00, Greeting: Good afternoon! -```javascript +``` --- @@ -281,19 +281,19 @@ In JavaScript conditionals, you'll use these comparison operators: ### Code Breakdown -```javascript +``` if (age >= 18) { console.log("You are an adult (18 or older)"); } else { console.log("You are a minor (under 18)"); } -```javascript +``` - **`if`** = Start of conditional statement - **`(age >= 18)`** = Condition that evaluates to true or false - **`{}`** = Code block executed if condition is true - **`else`** = Code block executed if condition is false -```javascript +``` if (grade >= 90) { console.log("Grade: A (90-100)"); } else if (grade >= 80) { @@ -305,18 +305,18 @@ if (grade >= 90) { } else { console.log("Grade: F (below 60)"); } -```javascript +``` - **`else if`** = Additional condition to check if the first was false - **Execution order** matters: JavaScript checks each condition in order and executes the first true one - **Only one block** executes, not multiple blocks -```javascript +``` if (username === "admin" && password === "secret123") { console.log("Login successful! Welcome, admin."); } else { console.log("Login failed! Invalid username or password."); } -```javascript +``` - **`&&`** = Logical AND operator (both conditions must be true) - **`===`** = Strict equality (both value AND type must match) - **Security** considerations: Never hardcode credentials in real programs @@ -324,12 +324,12 @@ if (username === "admin" && password === "secret123") { ### Comparison Operators Deep Dive **Loose vs Strict Equality:** -```javascript +``` console.log(5 == "5"); // true (values are the same after conversion) console.log(5 === "5"); // false (different types: number vs string) console.log(0 == false); // true (0 and false are both "falsy") console.log(0 === false); // false (different types) -```javascript +``` **Best Practice**: Use `===` (strict equality) in most cases to avoid unexpected type conversions. @@ -342,7 +342,7 @@ console.log(0 === false); // false (different types) | NOT | `!` | Reverse condition | `!true` | `false` | **More Examples:** -```javascript +``` // AND: All conditions must be true let age = 21; let hasID = true; @@ -364,11 +364,11 @@ let isLoggedIn = false; if (!isLoggedIn) { console.log("Please log in first"); } -```javascript +``` ### Nested Conditionals -```javascript +``` if (number > 0) { console.log("The number is positive"); if (number % 2 === 0) { // Nested if @@ -378,13 +378,13 @@ if (number > 0) { } } } -```javascript +``` - **Inner condition** only evaluated if outer condition is true - **Be careful** with nesting - too deep can be hard to read ### Switch Statement -```javascript +``` switch (dayOfWeek) { case 1: console.log("Today is Monday"); @@ -396,7 +396,7 @@ switch (dayOfWeek) { console.log("Invalid day number"); break; } -```javascript +``` - **Alternative to long if/else if** chains - **`break`** = Stops execution and exits switch - **Without break** = Falls through to next case ("fallthrough") @@ -404,27 +404,27 @@ switch (dayOfWeek) { ### Ternary Operator -```javascript +``` let result = score >= 60 ? "Pass" : "Fail"; -```javascript +``` - **Syntax**: `condition ? valueIfTrue : valueIfFalse` - **Same as**: -```javascript +``` let result; if (score >= 60) { result = "Pass"; } else { result = "Fail"; } -```javascript +``` **Chained Ternary (advanced):** -```javascript +``` let timeOfDay = 14; -let greeting = timeOfDay < 12 ? "Good morning!" : - timeOfDay < 18 ? "Good afternoon!" : +let greeting = timeOfDay < 12 ? "Good morning!" : + timeOfDay < 18 ? "Good afternoon!" : "Good evening!"; -```javascript +``` ### Truthy and Falsy Values @@ -453,7 +453,7 @@ All other values are "truthy", even `"false"` (string) and `[]` (empty array)! ### Best Practices for Conditionals **Use descriptive variable names:** -```javascript +``` // Good if (isAdult) { ... } if (isValidEmail) { ... } @@ -461,17 +461,17 @@ if (isValidEmail) { ... } // Avoid if (x) { ... } if (flag) { ... } -```javascript +``` **Keep conditions simple:** -```javascript +``` // Good - store complex condition in variable let canVote = age >= 18 && isCitizen && !isInPrison; if (canVote) { ... } // Avoid - hard to read if (age >= 18 && isCitizen && !isInPrison) { ... } -```javascript +``` **Consider switch vs if/else if:** - Use `switch` for exact value matching @@ -481,7 +481,7 @@ if (age >= 18 && isCitizen && !isInPrison) { ... } Try this complex conditional program: -```javascript +``` // A simple grading system with lots of conditions let studentName = "Alex"; let examScore = 88; @@ -547,11 +547,11 @@ if (overallScore >= 75 && participation) { } else { console.log("Not eligible for graduation, must repeat course"); } -```javascript +``` --- - **Excellent work! You now understand how to make your programs make intelligent decisions!** + **Excellent work! You now understand how to make your programs make intelligent decisions!** *Ready for the next challenge? Let's learn about loops and repetition!* @@ -578,40 +578,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```js -console.log("Hello, World!"); - -```js - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard javascript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/javascript/stage-1/level-6/lesson.md b/lessons/javascript/stage-1/level-6/lesson.md index 61ed360..e15ee8b 100644 --- a/lessons/javascript/stage-1/level-6/lesson.md +++ b/lessons/javascript/stage-1/level-6/lesson.md @@ -25,7 +25,7 @@ Time to make your programs repeat actions! Today you'll learn how to write code **Copy the following code into a new file called `loops.js`** -```javascript +``` console.log("=== For Loop - Counting ==="); // Basic for loop: for (initialization; condition; increment) for (let i = 1; i <= 5; i++) { @@ -86,7 +86,7 @@ do { tries++; menuChoice = Math.floor(Math.random() * 4) + 1; // Random 1-4 console.log("Menu attempt #" + tries + ": Option " + menuChoice); - + if (menuChoice === 3) { console.log("Option 3 selected! Exiting menu."); } @@ -162,19 +162,19 @@ for (let i = 0; i < items.length; i++) { // In a real program, we might do some work here console.log(" " + items[i] + " processed"); } -```javascript +``` --- ### How to Execute 1. **Run your program**: - ```bash + ``` node loops.js - ```java + ``` **Expected output:** -```javascript +``` === For Loop - Counting === Count: 1 Count: 2 @@ -193,7 +193,7 @@ Countdown: 4 Countdown: 3 Countdown: 2 Countdown: 1 -Blast off! +Blast off! === For Loop - Even Numbers === Even number: 2 @@ -260,16 +260,16 @@ Fruit: grape Fruit: mango === Nested Loops - Multiplication Table === -1 2 3 -2 4 6 -3 6 9 +1 2 3 +2 4 6 +3 6 9 === Pattern - Stars === -* -* * -* * * -* * * * -* * * * * +* +* * +* * * +* * * * +* * * * * === Looping with User Input Simulation === Processing item1... @@ -282,7 +282,7 @@ Processing item4... item4 processed Processing item5... item5 processed -```javascript +``` --- @@ -333,11 +333,11 @@ Processing item5... ### Code Breakdown -```javascript +``` for (let i = 1; i <= 5; i++) { console.log("Count: " + i); } -```javascript +``` - **`for`** = Loop keyword - **`let i = 1`** = Initialization: set up the counter variable - **`i <= 5`** = Condition: keep looping while this is true @@ -345,21 +345,21 @@ for (let i = 1; i <= 5; i++) { - **`{}`** = Code block that runs each iteration - **Loop execution**: 1, 2, 3, 4, 5 (stops when i becomes 6) -```javascript +``` while (count <= 5) { console.log("While count: " + count); count++; // Critical: must update the counter! } -```javascript +``` - **`while`** = Loop that continues while condition is true - **Condition checked first** before each iteration - **`count++`** = Must update counter inside the loop or it runs forever! -```javascript +``` do { console.log("Menu attempt #" + tries + ": Option " + menuChoice); } while (menuChoice !== 3 && tries < 10); -```javascript +``` - **`do`** = Code block executes first - **`while`** = Then condition is checked - **Result**: Block runs at least once regardless of condition @@ -367,7 +367,7 @@ do { ### For Loop Variations **Different increment patterns:** -```javascript +``` // Count by 5s for (let i = 0; i <= 25; i += 5) { console.log(i); // 0, 5, 10, 15, 20, 25 @@ -382,11 +382,11 @@ for (let i = 10; i > 0; i--) { for (let i = 0; i <= 1; i += 0.2) { console.log(i); // 0, 0.2, 0.4, 0.6, 0.8, 1 } -```javascript +``` ### Array Iteration Methods -```javascript +``` let fruits = ["apple", "banana", "orange"]; // Traditional for loop @@ -403,43 +403,43 @@ for (let fruit of fruits) { fruits.forEach(function(fruit) { console.log(fruit); }); -```javascript +``` **`array.length`** = Property that returns the number of elements in the array. ### Break and Continue **`break`** = Exits the loop completely: -```javascript +``` for (let i = 1; i <= 10; i++) { if (i === 5) { break; // Loop stops here } console.log(i); // Prints: 1, 2, 3, 4 } -```javascript +``` **`continue`** = Skips the rest of current iteration: -```javascript +``` for (let i = 1; i <= 5; i++) { if (i === 3) { continue; // Skip to next iteration } console.log(i); // Prints: 1, 2, 4, 5 (skips 3) } -```javascript +``` ### Nested Loops -```javascript +``` for (let i = 1; i <= 3; i++) { // Outer loop for (let j = 1; j <= 3; j++) { // Inner loop console.log("i=" + i + ", j=" + j); } } -```javascript +``` **Output:** -```javascript +``` i=1, j=1 i=1, j=2 i=1, j=3 @@ -449,13 +449,13 @@ i=2, j=3 i=3, j=1 i=3, j=2 i=3, j=3 -```javascript +``` - **Inner loop** completes all iterations for each outer loop iteration - **Total iterations**: 3 × 3 = 9 ### Random Numbers in JavaScript -```javascript +``` // Random integer between min and max (inclusive) function randomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; @@ -465,19 +465,19 @@ function randomInt(min, max) { console.log(randomInt(1, 6)); // Random die roll console.log(randomInt(1, 100)); // Random number 1-100 console.log(randomInt(10, 20)); // Random number 10-20 -```javascript +``` ### Loop Performance Considerations **Cache array length** (minor optimization): -```javascript +``` // Instead of this (length checked each iteration): for (let i = 0; i < myArray.length; i++) { ... } // Do this (length calculated once): let len = myArray.length; for (let i = 0; i < len; i++) { ... } -```javascript +``` ### Common Errors & Solutions @@ -515,14 +515,14 @@ for (let i = 0; i < len; i++) { ... } Try this complex loop program: -```javascript +``` console.log("=== Advanced Loop Examples ==="); // Prime number finder console.log("Prime numbers from 2 to 30:"); for (let num = 2; num <= 30; num++) { let isPrime = true; - + // Check if num is divisible by any number from 2 to sqrt(num) for (let divisor = 2; divisor <= Math.sqrt(num); divisor++) { if (num % divisor === 0) { @@ -530,7 +530,7 @@ for (let num = 2; num <= 30; num++) { break; // Found a divisor, not prime } } - + if (isPrime) { console.log(num + " is prime"); } @@ -571,11 +571,11 @@ for (let i = 1; i <= 5; i++) { } console.log(row); } -```javascript +``` --- - **Excellent work! You now understand how to repeat actions efficiently with loops!** + **Excellent work! You now understand how to repeat actions efficiently with loops!** *Ready for the next challenge? Let's learn about functions - the building blocks of reusable code!* @@ -599,40 +599,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```js -console.log("Hello, World!"); - -```js - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard javascript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/javascript/stage-1/level-7/lesson.md b/lessons/javascript/stage-1/level-7/lesson.md index 37a4919..0a5797d 100644 --- a/lessons/javascript/stage-1/level-7/lesson.md +++ b/lessons/javascript/stage-1/level-7/lesson.md @@ -26,7 +26,7 @@ Welcome to the world of functions! Today you'll learn how to organize your code **Copy the following code into a new file called `functions.js`** -```javascript +``` console.log("=== Basic Function Definition ==="); // Define a function that greets someone function greetUser() { @@ -157,7 +157,7 @@ function scopeDemo() { let localVariable = "I'm local!"; console.log("Inside function: " + globalVariable); console.log("Inside function: " + localVariable); - + // Functions can modify global variables globalVariable = "Modified from inside function!"; } @@ -177,7 +177,7 @@ function outerFunction(name) { function innerFunction() { return "Hello from inside!"; } - + return name + ", " + innerFunction(); } @@ -229,19 +229,19 @@ console.log("Doubled: " + doubled); // Process array using arrow function let squared = processArray(numbers, (x) => x * x); console.log("Squared: " + squared); -```javascript +``` --- ### How to Execute 1. **Run your program**: - ```bash + ``` node functions.js - ```java + ``` **Expected output:** -```javascript +``` === Basic Function Definition === Hello! Welcome to the wonderful world of functions! Hello! Welcome to the wonderful world of functions! @@ -296,7 +296,7 @@ Greeting: Hello, I'm Taylor Original: 1,2,3,4,5 Doubled: 2,4,6,8,10 Squared: 1,4,9,16,25 -```javascript +``` --- @@ -349,29 +349,29 @@ Squared: 1,4,9,16,25 ### Code Breakdown -```javascript +``` function greetUser() { console.log("Hello! Welcome to the wonderful world of functions!"); } -```javascript +``` - **`function`** = Keyword to declare a function - **`greetUser`** = Function name (follows variable naming rules) - **`()`** = Parameters (empty because no parameters needed) - **`{}`** = Function body (code that runs when function is called) - **No return** = Function runs code but doesn't return a value -```javascript +``` function greetByName(name) { console.log("Hello, " + name + "! Nice to meet you!"); } -```javascript +``` - **`name`** = Parameter (variable that receives the argument value) - **Parameters** = Variables defined in function declaration - **Arguments** = Actual values passed when calling the function -```javascript +``` let result1 = addNumbers(5, 3); -```javascript +``` - **`addNumbers(5, 3)`** = Function call with arguments - **`5` and `3`** = Arguments passed to the function - **Return value** = Value that function sends back @@ -380,51 +380,51 @@ let result1 = addNumbers(5, 3); ### Function Declaration vs Expression **Function Declaration (Traditional):** -```javascript +``` function add(a, b) { return a + b; } // Can be called before or after the declaration due to hoisting -```javascript +``` **Function Expression:** -```javascript +``` let add = function(a, b) { return a + b; }; // Must be defined before calling (no hoisting) -```javascript +``` ### Arrow Functions **Full syntax:** -```javascript +``` let add = (a, b) => { return a + b; }; -```javascript +``` **Shortened syntax (implicit return):** -```javascript +``` let add = (a, b) => a + b; // Returns a + b automatically let square = x => x * x; // Single parameter doesn't need parentheses let greet = () => "Hello!"; // No parameters need empty parentheses -```javascript +``` ### Function Parameters **Default parameters:** -```javascript +``` function greet(name, greeting = "Hello") { console.log(greeting + ", " + name + "!"); } greet("Alex"); // "Hello, Alex!" (greeting uses default) greet("Taylor", "Hi"); // "Hi, Taylor!" (greeting overridden) -```javascript +``` **Rest parameters (for multiple values):** -```javascript +``` function sum(...numbers) { let total = 0; for (let num of numbers) { @@ -435,23 +435,23 @@ function sum(...numbers) { console.log(sum(1, 2, 3)); // 6 console.log(sum(1, 2, 3, 4, 5)); // 15 -```javascript +``` ### Function Scope **Global scope:** -```javascript +``` let globalVar = "I'm accessible everywhere"; -```javascript +``` **Local scope:** -```javascript +``` function myFunction() { let localVar = "I'm only accessible inside this function"; // Can access both globalVar and localVar } // Can access globalVar but NOT localVar -```javascript +``` **Scope rules:** - Functions can access variables in their own scope @@ -462,23 +462,23 @@ function myFunction() { ### Return Values **Functions without return:** -```javascript +``` function sayHello() { console.log("Hello!"); } // Returns 'undefined' implicitly -```javascript +``` **Functions with return:** -```javascript +``` function getHello() { return "Hello!"; } // Returns "Hello!" which can be stored in a variable -```javascript +``` **Early return:** -```javascript +``` function divide(a, b) { if (b === 0) { console.log("Cannot divide by zero!"); @@ -486,13 +486,13 @@ function divide(a, b) { } return a / b; } -```javascript +``` ### Higher-Order Functions Functions that take other functions as parameters or return functions: -```javascript +``` // Function that takes another function as a parameter function executeTwice(func) { func(); @@ -504,28 +504,28 @@ function sayHello() { } executeTwice(sayHello); // Will output "Hello!" twice -```javascript +``` ### Pure vs Impure Functions **Pure function:** - Same input always gives same output - No side effects (doesn't modify external state) -```javascript +``` function add(a, b) { return a + b; // Pure function } -```javascript +``` **Impure function:** - May have side effects or depend on external state -```javascript +``` let count = 0; function increment() { count++; // Modifies external variable return count; } // Impure function -```javascript +``` ### Common Errors & Solutions @@ -540,7 +540,7 @@ function increment() { ### Best Practices for Functions **Function naming:** -```javascript +``` // Good - descriptive names function calculateArea(length, width) { ... } function isValidEmail(email) { ... } @@ -549,7 +549,7 @@ function sendNotification(message) { ... } // Avoid - vague names function doStuff() { ... } function process() { ... } -```javascript +``` **Function size:** - Keep functions focused on a single task @@ -557,7 +557,7 @@ function process() { ... } - If a function gets too long, consider breaking it into smaller ones **Single Responsibility Principle:** -```javascript +``` // Good - one purpose function calculateTax(amount, rate) { return amount * rate; @@ -570,13 +570,13 @@ function processOrder(order) { // ... other processing return total; } -```javascript +``` ### Advanced Challenge (For the Brave!) Try this comprehensive function example: -```javascript +``` // A comprehensive banking application using functions console.log("=== Banking Application with Functions ==="); @@ -595,7 +595,7 @@ function deposit(account, amount) { console.log("Deposit amount must be positive!"); return false; } - + account.balance += amount; account.transactions.push({ type: "deposit", @@ -603,7 +603,7 @@ function deposit(account, amount) { date: new Date().toLocaleDateString(), balanceAfter: account.balance }); - + console.log("$" + amount + " deposited. New balance: $" + account.balance); return true; } @@ -614,12 +614,12 @@ function withdraw(account, amount) { console.log("Withdrawal amount must be positive!"); return false; } - + if (amount > account.balance) { console.log("Insufficient funds! Current balance: $" + account.balance); return false; } - + account.balance -= amount; account.transactions.push({ type: "withdrawal", @@ -627,7 +627,7 @@ function withdraw(account, amount) { date: new Date().toLocaleDateString(), balanceAfter: account.balance }); - + console.log("$" + amount + " withdrawn. New balance: $" + account.balance); return true; } @@ -643,7 +643,7 @@ function getTransactionHistory(account) { console.log(account.name + "'s Transaction History:"); for (let i = 0; i < account.transactions.length; i++) { let transaction = account.transactions[i]; - console.log(transaction.date + " - " + transaction.type + ": $" + + console.log(transaction.date + " - " + transaction.type + ": $" + transaction.amount + " - Balance: $" + transaction.balanceAfter); } } @@ -652,7 +652,7 @@ function getTransactionHistory(account) { function transfer(fromAccount, toAccount, amount) { if (withdraw(fromAccount, amount)) { deposit(toAccount, amount); - console.log("Transfer of $" + amount + " from " + fromAccount.name + + console.log("Transfer of $" + amount + " from " + fromAccount.name + " to " + toAccount.name + " completed!"); return true; } @@ -672,11 +672,11 @@ checkBalance(taylorAccount); console.log(""); getTransactionHistory(alexAccount); -```javascript +``` --- - **Excellent work! You now understand how to organize code using functions - a fundamental skill for all programmers!** + **Excellent work! You now understand how to organize code using functions - a fundamental skill for all programmers!** *This completes Stage 1 of JavaScript learning! You've mastered the fundamentals of JavaScript programming. Great job!* @@ -703,40 +703,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```js -console.log("Hello, World!"); - -```js - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard javascript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/javascript/stage-2/level-1/lesson.md b/lessons/javascript/stage-2/level-1/lesson.md index 4d3d903..57e19a9 100644 --- a/lessons/javascript/stage-2/level-1/lesson.md +++ b/lessons/javascript/stage-2/level-1/lesson.md @@ -26,7 +26,7 @@ Welcome to Stage 2! You've mastered copying code - now it's time to think like a **Pseudocode** is a way to write programming logic in plain English (or your native language) before writing actual code. It's like writing a recipe or instructions for a task. **Example:** -```javascript +``` Algorithm: Make a sandwich 1. Get bread from pantry 2. Get peanut butter from fridge @@ -35,7 +35,7 @@ Algorithm: Make a sandwich 5. Spread jelly on the other bread slice 6. Put slices together 7. Enjoy your sandwich! -```javascript +``` This is much easier to understand than trying to write code first! @@ -51,25 +51,25 @@ This is much easier to understand than trying to write code first! ### How to Run 1. **Run the code**: - ```bash + ``` node hello.js - ```java + ``` **Expected output:** -```javascript +``` Hello, World! -```javascript +``` ## Algorithm 1: Greeting Program **Pseudocode:** -```javascript +``` Algorithm: Display Personal Greeting 1. Display "Hello! What's your name?" to the user 2. Get the user's name from input 3. Display "Nice to meet you, " followed by the user's name 4. Display "Welcome to programming!" -```javascript +``` **Your Task:** Create a JavaScript program that follows these exact steps. @@ -78,7 +78,7 @@ Algorithm: Display Personal Greeting ## Algorithm 2: Simple Calculator **Pseudocode:** -```javascript +``` Algorithm: Add Two Numbers 1. Ask user for first number 2. Get first number from user @@ -86,7 +86,7 @@ Algorithm: Add Two Numbers 4. Get second number from user 5. Calculate sum of the two numbers 6. Display "The sum is: " followed by the sum -```javascript +``` **Your Task:** Create a JavaScript program that implements this calculator. @@ -95,14 +95,14 @@ Algorithm: Add Two Numbers ## Algorithm 3: Age Calculator **Pseudocode:** -```javascript +``` Algorithm: Calculate Age in Days 1. Display "Enter your age in years: " 2. Get age in years from user 3. Calculate days = age × 365 4. Display "You are approximately " + days + " days old" 5. Display "That's a lot of days!" -```javascript +``` **Your Task:** Create a program that calculates approximate age in days. @@ -111,7 +111,7 @@ Algorithm: Calculate Age in Days ## Algorithm 4: Temperature Converter **Pseudocode:** -```javascript +``` Algorithm: Celsius to Fahrenheit Converter 1. Display "Enter temperature in Celsius: " 2. Get temperature in Celsius from user @@ -120,7 +120,7 @@ Algorithm: Celsius to Fahrenheit Converter 5. Display "°C = " 6. Display the Fahrenheit temperature 7. Display "°F" -```javascript +``` **Your Task:** Create a temperature conversion program. @@ -129,7 +129,7 @@ Algorithm: Celsius to Fahrenheit Converter ## Algorithm 5: Rectangle Area Calculator **Pseudocode:** -```javascript +``` Algorithm: Calculate Rectangle Area 1. Display "Rectangle Area Calculator" 2. Display "Enter length: " @@ -140,7 +140,7 @@ Algorithm: Calculate Rectangle Area 7. Calculate perimeter = 2 × (length + width) 8. Display "Area: " + area 9. Display "Perimeter: " + perimeter -```javascript +``` **Your Task:** Create a program that calculates both area and perimeter. @@ -149,7 +149,7 @@ Algorithm: Calculate Rectangle Area ## Algorithm 6: Simple Interest Calculator **Pseudocode:** -```javascript +``` Algorithm: Calculate Simple Interest 1. Display "Simple Interest Calculator" 2. Display "Enter principal amount: $" @@ -163,7 +163,7 @@ Algorithm: Calculate Simple Interest 10. Display "Principal: $" + principal 11. Display "Interest: $" + interest 12. Display "Total: $" + total -```javascript +``` **Your Task:** Implement the complete interest calculation. @@ -172,7 +172,7 @@ Algorithm: Calculate Simple Interest ## Algorithm 7: BMI Calculator **Pseudocode:** -```javascript +``` Algorithm: Calculate Body Mass Index 1. Display "BMI Calculator" 2. Display "Enter weight in kg: " @@ -189,7 +189,7 @@ Algorithm: Calculate Body Mass Index Display "Category: Overweight" 11. Else Display "Category: Obesity" -```javascript +``` **Your Task:** Create a program that calculates BMI with categorization. @@ -245,7 +245,7 @@ Algorithm: Calculate Body Mass Index ## Pseudocode Best Practices ### Good Pseudocode -```javascript +``` Algorithm: Process User Data 1. Get user's name 2. Get user's age @@ -254,18 +254,18 @@ Algorithm: Process User Data Else Display "Minor user" 4. Display "Data processed" -```javascript +``` ### Bad Pseudocode (Too Vague) -```javascript +``` Algorithm: Do stuff 1. Get things 2. Calculate something 3. Show results -```javascript +``` ### Good Pseudocode (Clear and Specific) -```javascript +``` Algorithm: Calculate BMI 1. Display "BMI Calculator" 2. Display "Enter weight in kg: " @@ -274,7 +274,7 @@ Algorithm: Calculate BMI 5. Get height from user 6. Calculate BMI = weight ÷ (height × height) 7. Display "Your BMI is: " + BMI -```javascript +``` --- @@ -286,7 +286,7 @@ Algorithm: Calculate BMI ### Algorithm 1: Greeting Program -```javascript +``` // For Node.js environment with readline-sync const readlineSync = require('readline-sync'); @@ -300,11 +300,11 @@ console.log("Nice to meet you, " + name); // Display "Welcome to programming!" console.log("Welcome to programming!"); -```javascript +``` ### Algorithm 2: Simple Calculator -```javascript +``` // For Node.js environment with readline-sync const readlineSync = require('readline-sync'); @@ -321,11 +321,11 @@ let sum = firstNum + secondNum; // Display "The sum is: " followed by the sum console.log("The sum is: " + sum); -```javascript +``` ### Algorithm 3: Age Calculator -```javascript +``` // For Node.js environment with readline-sync const readlineSync = require('readline-sync'); @@ -340,11 +340,11 @@ let days = age * 365; // Display messages console.log("You are approximately " + days + " days old"); console.log("That's a lot of days!"); -```javascript +``` ### Algorithm 4: Temperature Converter -```javascript +``` // For Node.js environment with readline-sync const readlineSync = require('readline-sync'); @@ -358,11 +358,11 @@ let fahrenheit = (celsius * 9/5) + 32; // Display the results console.log(celsius + "°C = " + fahrenheit + "°F"); -```javascript +``` ### Algorithm 5: Rectangle Area Calculator -```javascript +``` // For Node.js environment with readline-sync const readlineSync = require('readline-sync'); @@ -383,11 +383,11 @@ let perimeter = 2 * (length + width); // Display results console.log("Area: " + area); console.log("Perimeter: " + perimeter); -```javascript +``` ### Algorithm 6: Simple Interest Calculator -```javascript +``` // For Node.js environment with readline-sync const readlineSync = require('readline-sync'); @@ -412,11 +412,11 @@ let total = principal + interest; console.log("Principal: $" + principal.toFixed(2)); console.log("Interest: $" + interest.toFixed(2)); console.log("Total: $" + total.toFixed(2)); -```javascript +``` ### Algorithm 7: BMI Calculator -```javascript +``` // For Node.js environment with readline-sync const readlineSync = require('readline-sync'); @@ -444,7 +444,7 @@ if (bmi < 18.5) { } else { console.log("Category: Obesity"); } -```javascript +``` ### Common Translation Patterns @@ -489,25 +489,25 @@ if (bmi < 18.5) { ### Input/Output Patterns **Getting Numbers:** -```javascript +``` let age = parseFloat(readlineSync.question("Enter age: ")); -```javascript +``` **Getting Text:** -```javascript +``` let name = readlineSync.question("Enter name: "); -```javascript +``` **Displaying Results:** -```javascript +``` console.log("Result: " + result); console.log("Price: $" + price.toFixed(2)); console.log("Hello, " + name + "!"); -```javascript +``` --- - **Congratulations! You've translated your first pseudocode algorithms into working JavaScript programs!** + **Congratulations! You've translated your first pseudocode algorithms into working JavaScript programs!** *This is a major milestone - you're now thinking like a programmer! Next up: Variables in pseudocode!* @@ -527,40 +527,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```js -console.log("Hello, World!"); - -```js - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard javascript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/javascript/stage-2/level-2/lesson.md b/lessons/javascript/stage-2/level-2/lesson.md index 0e9827c..c6a0b49 100644 --- a/lessons/javascript/stage-2/level-2/lesson.md +++ b/lessons/javascript/stage-2/level-2/lesson.md @@ -26,25 +26,25 @@ Welcome to Level 2! Today we're focusing on how to handle variables in your pseu Variables in pseudocode follow simple patterns: **Declaration and assignment:** -```javascript +``` SET name TO "John" SET age TO 25 SET is_student TO TRUE -```javascript +``` **Reassignment:** -```javascript +``` SET age TO age + 1 SET total TO total + new_value SET is_student TO FALSE -```javascript +``` **Calculations with variables:** -```javascript +``` SET area TO length * width SET average TO (num1 + num2 + num3) / 3 SET is_adult TO age >= 18 -```javascript +``` --- @@ -58,19 +58,19 @@ SET is_adult TO age >= 18 ### How to Run 1. **Run the code**: - ```bash + ``` node hello.js - ```java + ``` **Expected output:** -```javascript +``` Hello, World! -```javascript +``` ## Algorithm 1: Simple Variable Swapping **Pseudocode:** -```javascript +``` Algorithm: Swap Two Variables 1. SET first_number TO 10 2. SET second_number TO 20 @@ -79,7 +79,7 @@ Algorithm: Swap Two Variables 5. SET first_number TO second_number 6. SET second_number TO temp 7. DISPLAY "After swap: first=" + first_number + ", second=" + second_number -```javascript +``` **Your Task:** Create a JavaScript program that demonstrates variable swapping. @@ -88,7 +88,7 @@ Algorithm: Swap Two Variables ## Algorithm 2: Running Total Calculator **Pseudocode:** -```javascript +``` Algorithm: Calculate Running Total 1. SET total TO 0 2. SET count TO 0 @@ -105,7 +105,7 @@ Algorithm: Calculate Running Total 13. DISPLAY "Total: " + total 14. DISPLAY "Count: " + count 15. DISPLAY "Average: " + average -```javascript +``` **Your Task:** Create a JavaScript program that calculates a running total and average. @@ -114,7 +114,7 @@ Algorithm: Calculate Running Total ## Algorithm 3: Temperature Tracker **Pseudocode:** -```javascript +``` Algorithm: Track Temperature Readings 1. SET min_temp TO 100 2. SET max_temp TO -100 @@ -136,7 +136,7 @@ Algorithm: Track Temperature Readings 13. IF current_temp > max_temp THEN SET max_temp TO current_temp 14. DISPLAY "Current: " + current_temp + ", Min: " + min_temp + ", Max: " + max_temp -```javascript +``` **Your Task:** Create a JavaScript program that tracks min/max temperatures. @@ -145,7 +145,7 @@ Algorithm: Track Temperature Readings ## Algorithm 4: Account Balance Tracker **Pseudocode:** -```javascript +``` Algorithm: Track Bank Account Balance 1. SET account_balance TO 1000 2. SET transaction_amount TO -50 @@ -160,7 +160,7 @@ Algorithm: Track Bank Account Balance 11. SET transaction_amount TO 150.25 12. SET account_balance TO account_balance + transaction_amount 13. DISPLAY "Balance after deposit: $" + account_balance -```javascript +``` **Your Task:** Create a JavaScript program that tracks account balance changes. @@ -169,7 +169,7 @@ Algorithm: Track Bank Account Balance ## Algorithm 5: Student Grade Calculator **Pseudocode:** -```javascript +``` Algorithm: Calculate Student Grade 1. SET total_points TO 0 2. SET possible_points TO 0 @@ -195,7 +195,7 @@ Algorithm: Calculate Student Grade 22. DISPLAY "Possible Points: " + possible_points 23. DISPLAY "Percentage: " + percentage 24. DISPLAY "Letter Grade: " + letter_grade -```javascript +``` **Your Task:** Create a JavaScript program that calculates student grades. @@ -204,7 +204,7 @@ Algorithm: Calculate Student Grade ## Algorithm 6: Counter Patterns **Pseudocode:** -```javascript +``` Algorithm: Different Counter Patterns 1. SET counter TO 1 2. SET even_counter TO 2 @@ -221,7 +221,7 @@ Algorithm: Different Counter Patterns 13. DISPLAY "Odd: " + odd_counter 14. SET odd_counter TO odd_counter + 2 15. END WHILE -```javascript +``` **Your Task:** Create a JavaScript program that demonstrates different counting patterns. @@ -230,7 +230,7 @@ Algorithm: Different Counter Patterns ## Algorithm 7: Accumulator Pattern **Pseudocode:** -```javascript +``` Algorithm: Calculate Statistics 1. SET sum TO 0 2. SET count TO 0 @@ -252,7 +252,7 @@ Algorithm: Calculate Statistics 18. DISPLAY "Count: " + count 19. DISPLAY "Product: " + product 20. DISPLAY "Average: " + average -```javascript +``` **Your Task:** Create a JavaScript program that demonstrates accumulator patterns. @@ -308,7 +308,7 @@ Algorithm: Calculate Statistics ### Algorithm 1: Simple Variable Swapping -```javascript +``` // Algorithm: Swap Two Variables let first_number = 10; let second_number = 20; @@ -320,11 +320,11 @@ first_number = second_number; second_number = temp; console.log("After swap: first=" + first_number + ", second=" + second_number); -```javascript +``` ### Algorithm 2: Running Total Calculator -```javascript +``` // Algorithm: Calculate Running Total let total = 0; let count = 0; @@ -346,11 +346,11 @@ let average = total / count; console.log("Total: " + total); console.log("Count: " + count); console.log("Average: " + average); -```javascript +``` ### Algorithm 3: Temperature Tracker -```javascript +``` // Algorithm: Track Temperature Readings let min_temp = 100; let max_temp = -100; @@ -381,11 +381,11 @@ if (current_temp > max_temp) { max_temp = current_temp; } console.log("Current: " + current_temp + ", Min: " + min_temp + ", Max: " + max_temp); -```javascript +``` ### Algorithm 4: Account Balance Tracker -```javascript +``` // Algorithm: Track Bank Account Balance let account_balance = 1000; @@ -404,11 +404,11 @@ console.log("Balance after withdrawal: $" + account_balance); transaction_amount = 150.25; account_balance = account_balance + transaction_amount; console.log("Balance after deposit: $" + account_balance); -```javascript +``` ### Algorithm 5: Student Grade Calculator -```javascript +``` // Algorithm: Calculate Student Grade let total_points = 0; let possible_points = 0; @@ -445,11 +445,11 @@ console.log("Total Points: " + total_points); console.log("Possible Points: " + possible_points); console.log("Percentage: " + percentage); console.log("Letter Grade: " + letter_grade); -```javascript +``` ### Algorithm 6: Counter Patterns -```javascript +``` // Algorithm: Different Counter Patterns let counter = 1; while (counter <= 5) { @@ -468,11 +468,11 @@ while (odd_counter <= 10) { console.log("Odd: " + odd_counter); odd_counter = odd_counter + 2; } -```javascript +``` ### Algorithm 7: Accumulator Pattern -```javascript +``` // Algorithm: Calculate Statistics let sum = 0; let count = 0; @@ -499,7 +499,7 @@ console.log("Sum: " + sum); console.log("Count: " + count); console.log("Product: " + product); console.log("Average: " + average); -```javascript +``` ### Variable Translation Patterns @@ -522,7 +522,7 @@ console.log("Average: " + average); --- - **Excellent work! You've mastered handling variables in pseudocode-to-code translation!** + **Excellent work! You've mastered handling variables in pseudocode-to-code translation!** *Next up: Mathematical operations in pseudocode!* @@ -542,40 +542,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```js -console.log("Hello, World!"); - -```js - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard javascript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/javascript/stage-2/level-3/lesson.md b/lessons/javascript/stage-2/level-3/lesson.md index 9235155..075abfb 100644 --- a/lessons/javascript/stage-2/level-3/lesson.md +++ b/lessons/javascript/stage-2/level-3/lesson.md @@ -26,36 +26,36 @@ Welcome to Level 3! Today we're focusing on mathematical operations in pseudocod Mathematical expressions in pseudocode follow standard notation: **Basic operations:** -```javascript +``` SET result TO 5 + 3 SET result TO 10 - 4 SET result TO 6 * 7 SET result TO 15 / 3 SET remainder TO 17 MOD 5 -```javascript +``` **Complex expressions:** -```javascript +``` SET area TO length * width SET volume TO length * width * height SET average TO (num1 + num2 + num3) / 3 SET tax TO price * 0.08 SET discount TO original_price * discount_rate -```javascript +``` **Order of operations:** -```javascript +``` SET result TO 2 + 3 * 4 // result = 14 (not 20), multiplication first SET result TO (2 + 3) * 4 // result = 20, parentheses override SET result TO 10 / 2 + 3 // result = 8, division first -```javascript +``` **Mathematical functions:** -```javascript +``` SET result TO POWER(2, 3) // 2 to the power of 3 SET result TO SQRT(16) // square root of 16 SET result TO ROUND(3.7) // round to nearest integer -```javascript +``` --- @@ -69,19 +69,19 @@ SET result TO ROUND(3.7) // round to nearest integer ### How to Run 1. **Run the code**: - ```bash + ``` node hello.js - ```java + ``` **Expected output:** -```javascript +``` Hello, World! -```javascript +``` ## Algorithm 1: Complex Arithmetic Expression **Pseudocode:** -```javascript +``` Algorithm: Evaluate Complex Expression 1. SET a TO 10 2. SET b TO 5 @@ -92,7 +92,7 @@ Algorithm: Evaluate Complex Expression 7. DISPLAY "Result without parentheses: " + result2 8. SET result3 TO ((a + b) * c - a) / c 9. DISPLAY "Result with different grouping: " + result3 -```javascript +``` **Your Task:** Create a JavaScript program that evaluates complex arithmetic expressions. @@ -101,7 +101,7 @@ Algorithm: Evaluate Complex Expression ## Algorithm 2: Quadratic Formula Calculator **Pseudocode:** -```javascript +``` Algorithm: Solve Quadratic Equation 1. SET a TO 1 2. SET b TO -5 @@ -112,7 +112,7 @@ Algorithm: Solve Quadratic Equation 7. SET root2 TO (-b - sqrt_discriminant) / (2 * a) 8. DISPLAY "Root 1: " + root1 9. DISPLAY "Root 2: " + root2 -```javascript +``` **Your Task:** Create a JavaScript program that solves quadratic equations using the quadratic formula. @@ -121,7 +121,7 @@ Algorithm: Solve Quadratic Equation ## Algorithm 3: Compound Interest Calculator **Pseudocode:** -```javascript +``` Algorithm: Calculate Compound Interest 1. SET principal TO 1000 2. SET rate TO 0.05 @@ -132,7 +132,7 @@ Algorithm: Calculate Compound Interest 7. DISPLAY "Principal: $" + principal 8. DISPLAY "Final Amount: $" + amount 9. DISPLAY "Interest Earned: $" + interest -```javascript +``` **Your Task:** Create a JavaScript program that calculates compound interest. @@ -141,7 +141,7 @@ Algorithm: Calculate Compound Interest ## Algorithm 4: Geometric Calculations **Pseudocode:** -```javascript +``` Algorithm: Calculate Geometric Properties 1. SET radius TO 5 2. SET side TO 4 @@ -155,7 +155,7 @@ Algorithm: Calculate Geometric Properties 10. DISPLAY "Circle - Area: " + circle_area + ", Circumference: " + circle_circumference 11. DISPLAY "Square - Area: " + square_area + ", Perimeter: " + square_perimeter 12. DISPLAY "Triangle - Area: " + triangle_area -```javascript +``` **Your Task:** Create a JavaScript program that calculates geometric properties. @@ -164,7 +164,7 @@ Algorithm: Calculate Geometric Properties ## Algorithm 5: Physics Formula Calculator **Pseudocode:** -```javascript +``` Algorithm: Physics Calculations 1. SET mass TO 5.5 2. SET velocity TO 10 @@ -178,7 +178,7 @@ Algorithm: Physics Calculations 10. DISPLAY "Force: " + force 11. DISPLAY "Distance: " + distance 12. DISPLAY "Momentum: " + momentum -```javascript +``` **Your Task:** Create a JavaScript program that calculates physics formulas. @@ -187,7 +187,7 @@ Algorithm: Physics Calculations ## Algorithm 6: Temperature Conversion with Multiple Formulas **Pseudocode:** -```javascript +``` Algorithm: Multiple Temperature Conversions 1. SET celsius TO 25 2. SET fahrenheit TO celsius * 9 / 5 + 32 @@ -199,7 +199,7 @@ Algorithm: Multiple Temperature Conversions 8. DISPLAY "Kelvin: " + kelvin 9. DISPLAY "F to C: " + celsius_from_f 10. DISPLAY "K to C: " + celsius_from_k -```javascript +``` **Your Task:** Create a JavaScript program that performs multiple temperature conversions. @@ -208,7 +208,7 @@ Algorithm: Multiple Temperature Conversions ## Algorithm 7: Statistical Calculations **Pseudocode:** -```javascript +``` Algorithm: Calculate Statistics for Three Numbers 1. SET num1 TO 10 2. SET num2 TO 20 @@ -225,7 +225,7 @@ Algorithm: Calculate Statistics for Three Numbers 13. DISPLAY "Range: " + range 14. DISPLAY "Variance: " + variance 15. DISPLAY "Standard Deviation: " + std_deviation -```javascript +``` **Your Task:** Create a JavaScript program that calculates statistical measures. @@ -282,7 +282,7 @@ Algorithm: Calculate Statistics for Three Numbers ### Algorithm 1: Complex Arithmetic Expression -```javascript +``` // Algorithm: Evaluate Complex Expression let a = 10; let b = 5; @@ -296,11 +296,11 @@ console.log("Result without parentheses: " + result2); let result3 = ((a + b) * c - a) / c; console.log("Result with different grouping: " + result3); -```javascript +``` ### Algorithm 2: Quadratic Formula Calculator -```javascript +``` // Algorithm: Solve Quadratic Equation let a = 1; let b = -5; @@ -313,11 +313,11 @@ let root2 = (-b - sqrt_discriminant) / (2 * a); console.log("Root 1: " + root1); console.log("Root 2: " + root2); -```javascript +``` ### Algorithm 3: Compound Interest Calculator -```javascript +``` // Algorithm: Calculate Compound Interest let principal = 1000; let rate = 0.05; @@ -330,11 +330,11 @@ let interest = amount - principal; console.log("Principal: $" + principal); console.log("Final Amount: $" + amount.toFixed(2)); console.log("Interest Earned: $" + interest.toFixed(2)); -```javascript +``` ### Algorithm 4: Geometric Calculations -```javascript +``` // Algorithm: Calculate Geometric Properties let radius = 5; let side = 4; @@ -350,11 +350,11 @@ let triangle_area = 0.5 * base * height; console.log("Circle - Area: " + circle_area.toFixed(2) + ", Circumference: " + circle_circumference.toFixed(2)); console.log("Square - Area: " + square_area + ", Perimeter: " + square_perimeter); console.log("Triangle - Area: " + triangle_area); -```javascript +``` ### Algorithm 5: Physics Formula Calculator -```javascript +``` // Algorithm: Physics Calculations let mass = 5.5; let velocity = 10; @@ -370,11 +370,11 @@ console.log("Kinetic Energy: " + kinetic_energy); console.log("Force: " + force); console.log("Distance: " + distance); console.log("Momentum: " + momentum); -```javascript +``` ### Algorithm 6: Temperature Conversion with Multiple Formulas -```javascript +``` // Algorithm: Multiple Temperature Conversions let celsius = 25; let fahrenheit = celsius * 9 / 5 + 32; @@ -387,11 +387,11 @@ console.log("Fahrenheit: " + fahrenheit); console.log("Kelvin: " + kelvin); console.log("F to C: " + celsius_from_f); console.log("K to C: " + celsius_from_k); -```javascript +``` ### Algorithm 7: Statistical Calculations -```javascript +``` // Algorithm: Calculate Statistics for Three Numbers let num1 = 10; let num2 = 20; @@ -410,7 +410,7 @@ console.log("Average: " + average); console.log("Range: " + range); console.log("Variance: " + variance); console.log("Standard Deviation: " + std_deviation.toFixed(2)); -```javascript +``` ### Mathematical Operation Translation Patterns @@ -435,7 +435,7 @@ console.log("Standard Deviation: " + std_deviation.toFixed(2)); --- - **Excellent work! You've mastered translating mathematical operations from pseudocode to JavaScript!** + **Excellent work! You've mastered translating mathematical operations from pseudocode to JavaScript!** *Next up: Input/Output operations in pseudocode!* @@ -455,40 +455,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```js -console.log("Hello, World!"); - -```js - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard javascript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/javascript/stage-2/level-4/lesson.md b/lessons/javascript/stage-2/level-4/lesson.md index 22e5f17..5b9ae51 100644 --- a/lessons/javascript/stage-2/level-4/lesson.md +++ b/lessons/javascript/stage-2/level-4/lesson.md @@ -26,24 +26,24 @@ Welcome to Level 4! Today we're focusing on input/output operations in pseudocod Input/Output expressions in pseudocode follow these patterns: **Input operations:** -```javascript +``` INPUT user_name INPUT age SET email TO INPUT("Enter your email: ") SET number TO INPUT_INTEGER("Enter a number: ") SET choice TO INPUT_CHOICE("A, B, C") -```javascript +``` **Output operations:** -```javascript +``` OUTPUT "Hello, " + user_name OUTPUT "Your age is: " + age DISPLAY message PRINT formatted_output -```javascript +``` **Combined I/O:** -```javascript +``` OUTPUT "Enter your name: " INPUT name IF name IS EMPTY THEN @@ -51,7 +51,7 @@ IF name IS EMPTY THEN ELSE OUTPUT "Hello, " + name + "!" ENDIF -```javascript +``` --- @@ -65,19 +65,19 @@ ENDIF ### How to Run 1. **Run the code**: - ```bash + ``` node hello.js - ```java + ``` **Expected output:** -```javascript +``` Hello, World! -```javascript +``` ## Algorithm 1: Simple Input Validation **Pseudocode:** -```javascript +``` Algorithm: Validate User Age 1. OUTPUT "Please enter your age: " 2. INPUT age @@ -86,7 +86,7 @@ Algorithm: Validate User Age 5. STOP 5. ENDIF 6. OUTPUT "Thank you! You are " + age + " years old." -```javascript +``` **Your Task:** Create a JavaScript program that validates user age input. @@ -95,7 +95,7 @@ Algorithm: Validate User Age ## Algorithm 2: User Information Form **Pseudocode:** -```javascript +``` Algorithm: Collect User Information 1. OUTPUT "User Information Form" 2. OUTPUT "===================" @@ -114,7 +114,7 @@ Algorithm: Collect User Information 15. OUTPUT "Email: " + email 16. OUTPUT "Favorite Color: " + color 17. OUTPUT "Form submitted successfully!" -```javascript +``` **Your Task:** Create a JavaScript program that collects and displays user information. @@ -123,7 +123,7 @@ Algorithm: Collect User Information ## Algorithm 3: Number Validation Loop **Pseudocode:** -```javascript +``` Algorithm: Get Valid Number 1. SET valid_input TO FALSE 2. WHILE NOT valid_input DO @@ -136,7 +136,7 @@ Algorithm: Get Valid Number 9. OUTPUT "Invalid! Please enter a positive number." 10. ENDIF 11. ENDWHILE -```javascript +``` **Your Task:** Create a JavaScript program that keeps asking for input until valid. @@ -145,7 +145,7 @@ Algorithm: Get Valid Number ## Algorithm 4: Grade Calculator with Input **Pseudocode:** -```javascript +``` Algorithm: Calculate Letter Grade 1. OUTPUT "Grade Calculator" 2. OUTPUT "===============" @@ -163,7 +163,7 @@ Algorithm: Calculate Letter Grade 14. OUTPUT "Score: " + score + "/" + total_points 15. OUTPUT "Percentage: " + percentage + "%" 16. OUTPUT "Letter Grade: " + letter_grade -```javascript +``` **Your Task:** Create a JavaScript program that calculates grades from user input. @@ -172,7 +172,7 @@ Algorithm: Calculate Letter Grade ## Algorithm 5: Temperature Converter with Menu **Pseudocode:** -```javascript +``` Algorithm: Temperature Converter Menu 1. OUTPUT "Temperature Converter" 2. OUTPUT "1. Celsius to Fahrenheit" @@ -192,7 +192,7 @@ Algorithm: Temperature Converter Menu 12. ELSE 16. OUTPUT "Invalid choice! Please enter 1 or 2." 17. ENDIF -```javascript +``` **Your Task:** Create a JavaScript program with a menu-based temperature converter. @@ -201,7 +201,7 @@ Algorithm: Temperature Converter Menu ## Algorithm 6: Input Validation with Multiple Fields **Pseudocode:** -```javascript +``` Algorithm: Validate Contact Information 1. SET is_valid TO TRUE 2. OUTPUT "Contact Information Form" @@ -228,7 +228,7 @@ Algorithm: Validate Contact Information 23. ELSE 24. OUTPUT "Form has errors. Please fix and resubmit." 25. ENDIF -```javascript +``` **Your Task:** Create a JavaScript program that validates multiple input fields. @@ -237,7 +237,7 @@ Algorithm: Validate Contact Information ## Algorithm 7: Calculator with User Interaction **Pseudocode:** -```javascript +``` Algorithm: Interactive Calculator 1. OUTPUT "Simple Calculator" 2. OUTPUT "Enter first number: " @@ -265,7 +265,7 @@ Algorithm: Interactive Calculator 24. IF NOT has_error THEN 25. OUTPUT num1 + " " + operator + " " + num2 + " = " + result 26. ENDIF -```javascript +``` **Your Task:** Create a JavaScript program that simulates a basic calculator with error handling. @@ -323,7 +323,7 @@ Algorithm: Interactive Calculator ### Algorithm 1: Simple Input Validation -```javascript +``` // For Node.js environment with readline-sync const readlineSync = require('readline-sync'); @@ -336,11 +336,11 @@ if (age < 0 || age > 150) { } else { console.log("Thank you! You are " + age + " years old."); } -```javascript +``` ### Algorithm 2: User Information Form -```javascript +``` // For Node.js environment with readline-sync const readlineSync = require('readline-sync'); @@ -367,11 +367,11 @@ console.log("Age: " + age); console.log("Email: " + email); console.log("Favorite Color: " + color); console.log("Form submitted successfully!"); -```javascript +``` ### Algorithm 3: Number Validation Loop -```javascript +``` // For Node.js environment with readline-sync const readlineSync = require('readline-sync'); @@ -381,7 +381,7 @@ let valid_input = false; while (!valid_input) { console.log("Enter a positive number: "); let number = parseFloat(readlineSync.question()); - + if (number > 0) { valid_input = true; console.log("Valid number entered: " + number); @@ -389,11 +389,11 @@ while (!valid_input) { console.log("Invalid! Please enter a positive number."); } } -```javascript +``` ### Algorithm 4: Grade Calculator with Input -```javascript +``` // For Node.js environment with readline-sync const readlineSync = require('readline-sync'); @@ -423,11 +423,11 @@ if (percentage >= 90) { console.log("Score: " + score + "/" + total_points); console.log("Percentage: " + percentage.toFixed(2) + "%"); console.log("Letter Grade: " + letter_grade); -```javascript +``` ### Algorithm 5: Temperature Converter with Menu -```javascript +``` // For Node.js environment with readline-sync const readlineSync = require('readline-sync'); @@ -452,11 +452,11 @@ if (choice === 1) { } else { console.log("Invalid choice! Please enter 1 or 2."); } -```javascript +``` ### Algorithm 6: Input Validation with Multiple Fields -```javascript +``` // For Node.js environment with readline-sync const readlineSync = require('readline-sync'); @@ -494,11 +494,11 @@ if (is_valid) { } else { console.log("Form has errors. Please fix and resubmit."); } -```javascript +``` ### Algorithm 7: Calculator with User Interaction -```javascript +``` // For Node.js environment with readline-sync const readlineSync = require('readline-sync'); @@ -538,7 +538,7 @@ if (operator === "+") { if (!has_error) { console.log(num1 + " " + operator + " " + num2 + " = " + result); } -```javascript +``` ### I/O Operation Translation Patterns @@ -564,7 +564,7 @@ if (!has_error) { --- - **Excellent work! You've mastered translating input/output operations from pseudocode to JavaScript!** + **Excellent work! You've mastered translating input/output operations from pseudocode to JavaScript!** *Next up: Decision pseudocode!* @@ -584,40 +584,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```js -console.log("Hello, World!"); - -```js - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard javascript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/javascript/stage-2/level-5/lesson.md b/lessons/javascript/stage-2/level-5/lesson.md index 2250352..1b73aad 100644 --- a/lessons/javascript/stage-2/level-5/lesson.md +++ b/lessons/javascript/stage-2/level-5/lesson.md @@ -26,23 +26,23 @@ Welcome to Level 5! Today we're focusing on decision-making operations in pseudo Decision expressions in pseudocode follow these patterns: **Simple if statements:** -```javascript +``` IF condition THEN DO something ENDIF -```javascript +``` **If-else statements:** -```javascript +``` IF condition THEN DO something ELSE DO something else ENDIF -```javascript +``` **Multiple conditions:** -```javascript +``` IF condition1 THEN DO something ELSE IF condition2 THEN @@ -50,19 +50,19 @@ ELSE IF condition2 THEN ELSE DO default action ENDIF -```javascript +``` **Complex conditions:** -```javascript +``` IF (age >= 18) AND (has_license) THEN OUTPUT "Can drive" ELSE OUTPUT "Cannot drive" ENDIF -```javascript +``` **Nested conditions:** -```javascript +``` IF weather = "sunny" THEN IF temperature > 80 THEN OUTPUT "Hot and sunny - beach time!" @@ -72,7 +72,7 @@ IF weather = "sunny" THEN ELSE OUTPUT "Stay inside" ENDIF -```javascript +``` --- @@ -86,19 +86,19 @@ ENDIF ### How to Run 1. **Run the code**: - ```bash + ``` node hello.js - ```java + ``` **Expected output:** -```javascript +``` Hello, World! -```javascript +``` ## Algorithm 1: Simple Age Check **Pseudocode:** -```javascript +``` Algorithm: Determine Life Stage 1. INPUT age 2. IF age < 13 THEN @@ -110,7 +110,7 @@ Algorithm: Determine Life Stage 8. ELSE 9. OUTPUT "Senior" 10. ENDIF -```javascript +``` **Your Task:** Create a JavaScript program that categorizes by age. @@ -119,7 +119,7 @@ Algorithm: Determine Life Stage ## Algorithm 2: Grade Determination **Pseudocode:** -```javascript +``` Algorithm: Assign Letter Grade 1. INPUT numeric_grade 2. IF numeric_grade >= 97 THEN @@ -148,7 +148,7 @@ Algorithm: Assign Letter Grade 24. SET letter_grade TO "F" 25. ENDIF 26. OUTPUT "Grade: " + letter_grade -```javascript +``` **Your Task:** Create a JavaScript program that determines letter grades. @@ -157,7 +157,7 @@ Algorithm: Assign Letter Grade ## Algorithm 3: Shopping Discount Calculator **Pseudocode:** -```javascript +``` Algorithm: Calculate Shopping Discount 1. INPUT total_amount 2. INPUT customer_type // "regular", "premium", "vip" @@ -188,7 +188,7 @@ Algorithm: Calculate Shopping Discount 27. OUTPUT "Original: $" + total_amount 28. OUTPUT "Discount: " + (discount_rate * 100) + "%" 29. OUTPUT "Final: $" + final_amount -```javascript +``` **Your Task:** Create a JavaScript program with nested decision logic for discounts. @@ -197,7 +197,7 @@ Algorithm: Calculate Shopping Discount ## Algorithm 4: Weather Advisory **Pseudocode:** -```javascript +``` Algorithm: Weather Advisory System 1. INPUT temperature 2. INPUT is_raining @@ -228,7 +228,7 @@ Algorithm: Weather Advisory System 27. IF wind_speed > 25 THEN 28. OUTPUT "High winds - Secure loose objects" 29. ENDIF -```javascript +``` **Your Task:** Create a JavaScript program that gives weather advisory. @@ -237,7 +237,7 @@ Algorithm: Weather Advisory System ## Algorithm 5: Password Validator **Pseudocode:** -```javascript +``` Algorithm: Validate Password Strength 1. INPUT password 2. SET has_uppercase TO FALSE @@ -281,7 +281,7 @@ Algorithm: Validate Password Strength 40. OUTPUT "- Must contain special character" 41. ENDIF 42. ENDIF -```javascript +``` **Your Task:** Create a JavaScript program that validates password strength. @@ -290,7 +290,7 @@ Algorithm: Validate Password Strength ## Algorithm 6: Transportation Advisor **Pseudocode:** -```javascript +``` Algorithm: Recommend Transportation 1. INPUT distance // in miles 2. INPUT weather_condition // "good", "bad", "severe" @@ -311,7 +311,7 @@ Algorithm: Recommend Transportation 17. ELSE 18. OUTPUT "Consider public transit or taxi" 19. ENDIF -```javascript +``` **Your Task:** Create a JavaScript program that recommends transportation. @@ -320,7 +320,7 @@ Algorithm: Recommend Transportation ## Algorithm 7: Complex Business Logic **Pseudocode:** -```javascript +``` Algorithm: Process Order 1. INPUT order_amount 2. INPUT customer_type // "new", "returning", "loyal" @@ -354,7 +354,7 @@ Algorithm: Process Order 30. ELSE 30. OUTPUT "Priority Processing: No" 31. ENDIF -```javascript +``` **Your Task:** Create a JavaScript program with complex business logic. @@ -412,7 +412,7 @@ Algorithm: Process Order ### Algorithm 1: Simple Age Check -```javascript +``` // For Node.js environment with readline-sync const readlineSync = require('readline-sync'); @@ -428,11 +428,11 @@ if (age < 13) { } else { console.log("Senior"); } -```javascript +``` ### Algorithm 2: Grade Determination -```javascript +``` // For Node.js environment with readline-sync const readlineSync = require('readline-sync'); @@ -467,11 +467,11 @@ if (numeric_grade >= 97) { } console.log("Grade: " + letter_grade); -```javascript +``` ### Algorithm 3: Shopping Discount Calculator -```javascript +``` // For Node.js environment with readline-sync const readlineSync = require('readline-sync'); @@ -509,11 +509,11 @@ let final_amount = total_amount - discount_amount; console.log("Original: $" + total_amount.toFixed(2)); console.log("Discount: " + (discount_rate * 100) + "%"); console.log("Final: $" + final_amount.toFixed(2)); -```javascript +``` ### Algorithm 4: Weather Advisory -```javascript +``` // For Node.js environment with readline-sync const readlineSync = require('readline-sync'); @@ -550,11 +550,11 @@ if (temperature > 90) { if (wind_speed > 25) { console.log("High winds - Secure loose objects"); } -```javascript +``` ### Algorithm 5: Password Validator -```javascript +``` // For Node.js environment with readline-sync const readlineSync = require('readline-sync'); @@ -594,11 +594,11 @@ if (length_ok && has_uppercase && has_lowercase && has_digit && has_special) { if (!has_digit) console.log("- Must contain digit"); if (!has_special) console.log("- Must contain special character"); } -```javascript +``` ### Algorithm 6: Transportation Advisor -```javascript +``` // For Node.js environment with readline-sync const readlineSync = require('readline-sync'); @@ -624,11 +624,11 @@ if (purpose === "emergency") { } else { console.log("Consider public transit or taxi"); } -```javascript +``` ### Algorithm 7: Complex Business Logic -```javascript +``` // For Node.js environment with readline-sync const readlineSync = require('readline-sync'); @@ -672,7 +672,7 @@ if (is_priority_processing) { } else { console.log("Priority Processing: No"); } -```javascript +``` ### Decision Operation Translation Patterns @@ -700,7 +700,7 @@ if (is_priority_processing) { --- - **Excellent work! You've mastered translating decision operations from pseudocode to JavaScript!** + **Excellent work! You've mastered translating decision operations from pseudocode to JavaScript!** *Next up: Loop pseudocode!* @@ -720,40 +720,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```js -console.log("Hello, World!"); - -```js - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard javascript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/javascript/stage-2/level-6/lesson.md b/lessons/javascript/stage-2/level-6/lesson.md index 60777de..1d04e79 100644 --- a/lessons/javascript/stage-2/level-6/lesson.md +++ b/lessons/javascript/stage-2/level-6/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Javascript:** -```javascript +``` ALGORITHM: Loop Algorithms BEGIN @@ -39,7 +39,7 @@ BEGIN // Translate step by step into Javascript // Test with sample inputs END -```javascript +``` **Implementation Steps:** 1. Analyze what the algorithm does @@ -54,14 +54,14 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` node hello.js - ```java + ``` **Expected output:** -```javascript +``` Hello, World! -```javascript +``` ### How to Approach This @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in Javascript 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```javascript +``` PSEUDOCODE: READ number IF number > 0 THEN @@ -168,7 +168,7 @@ PSEUDOCODE: ELSE PRINT "Not positive" END IF -```javascript +``` This becomes structured Javascript code following the language syntax. @@ -211,40 +211,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```js -console.log("Hello, World!"); - -```js - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard javascript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/javascript/stage-2/level-7/lesson.md b/lessons/javascript/stage-2/level-7/lesson.md index db9a640..86ad6f6 100644 --- a/lessons/javascript/stage-2/level-7/lesson.md +++ b/lessons/javascript/stage-2/level-7/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Javascript:** -```javascript +``` ALGORITHM: Function Design BEGIN @@ -39,7 +39,7 @@ BEGIN // Translate step by step into Javascript // Test with sample inputs END -```javascript +``` **Implementation Steps:** 1. Analyze what the algorithm does @@ -54,14 +54,14 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` node hello.js - ```java + ``` **Expected output:** -```javascript +``` Hello, World! -```javascript +``` ### How to Approach This @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in Javascript 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```javascript +``` PSEUDOCODE: READ number IF number > 0 THEN @@ -168,7 +168,7 @@ PSEUDOCODE: ELSE PRINT "Not positive" END IF -```javascript +``` This becomes structured Javascript code following the language syntax. @@ -211,40 +211,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```js -console.log("Hello, World!"); - -```js - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard javascript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/javascript/stage-3/level-1/lesson.md b/lessons/javascript/stage-3/level-1/lesson.md index 41780a9..55bcc34 100644 --- a/lessons/javascript/stage-3/level-1/lesson.md +++ b/lessons/javascript/stage-3/level-1/lesson.md @@ -51,14 +51,14 @@ Simple Problem Analysis - Design an algorithm to solve this problem, then implem ### How to Run 1. **Run the code**: - ```bash + ``` node hello.js - ```java + ``` **Expected output:** -```javascript +``` Hello, World! -```javascript +``` ### How to Approach This @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```javascript +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -169,7 +169,7 @@ BEGIN - Step 3 4. Display results END -```javascript +``` Then translate this directly to Javascript code. @@ -212,40 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```js -console.log("Hello, World!"); - -```js - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard javascript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/javascript/stage-3/level-2/lesson.md b/lessons/javascript/stage-3/level-2/lesson.md index 22e5179..ecb848a 100644 --- a/lessons/javascript/stage-3/level-2/lesson.md +++ b/lessons/javascript/stage-3/level-2/lesson.md @@ -51,14 +51,14 @@ Data Structure Planning - Design an algorithm to solve this problem, then implem ### How to Run 1. **Run the code**: - ```bash + ``` node hello.js - ```java + ``` **Expected output:** -```javascript +``` Hello, World! -```javascript +``` ### How to Approach This @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```javascript +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -169,7 +169,7 @@ BEGIN - Step 3 4. Display results END -```javascript +``` Then translate this directly to Javascript code. @@ -212,40 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```js -console.log("Hello, World!"); - -```js - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard javascript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/javascript/stage-3/level-3/lesson.md b/lessons/javascript/stage-3/level-3/lesson.md index 06a6348..25c441c 100644 --- a/lessons/javascript/stage-3/level-3/lesson.md +++ b/lessons/javascript/stage-3/level-3/lesson.md @@ -51,14 +51,14 @@ Mathematical Problems - Design an algorithm to solve this problem, then implemen ### How to Run 1. **Run the code**: - ```bash + ``` node hello.js - ```java + ``` **Expected output:** -```javascript +``` Hello, World! -```javascript +``` ### How to Approach This @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```javascript +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -169,7 +169,7 @@ BEGIN - Step 3 4. Display results END -```javascript +``` Then translate this directly to Javascript code. @@ -212,40 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```js -console.log("Hello, World!"); - -```js - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard javascript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/javascript/stage-3/level-4/lesson.md b/lessons/javascript/stage-3/level-4/lesson.md index 365a2aa..0c6a02f 100644 --- a/lessons/javascript/stage-3/level-4/lesson.md +++ b/lessons/javascript/stage-3/level-4/lesson.md @@ -51,14 +51,14 @@ Text Processing Problems - Design an algorithm to solve this problem, then imple ### How to Run 1. **Run the code**: - ```bash + ``` node hello.js - ```java + ``` **Expected output:** -```javascript +``` Hello, World! -```javascript +``` ### How to Approach This @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```javascript +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -169,7 +169,7 @@ BEGIN - Step 3 4. Display results END -```javascript +``` Then translate this directly to Javascript code. @@ -212,40 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```js -console.log("Hello, World!"); - -```js - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard javascript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/javascript/stage-3/level-5/lesson.md b/lessons/javascript/stage-3/level-5/lesson.md index 749d2c2..5097e6c 100644 --- a/lessons/javascript/stage-3/level-5/lesson.md +++ b/lessons/javascript/stage-3/level-5/lesson.md @@ -51,14 +51,14 @@ Logic Problems - Design an algorithm to solve this problem, then implement it. ### How to Run 1. **Run the code**: - ```bash + ``` node hello.js - ```java + ``` **Expected output:** -```javascript +``` Hello, World! -```javascript +``` ### How to Approach This @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```javascript +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -169,7 +169,7 @@ BEGIN - Step 3 4. Display results END -```javascript +``` Then translate this directly to Javascript code. @@ -212,40 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```js -console.log("Hello, World!"); - -```js - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard javascript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/javascript/stage-3/level-6/lesson.md b/lessons/javascript/stage-3/level-6/lesson.md index a6324d7..ed6bac7 100644 --- a/lessons/javascript/stage-3/level-6/lesson.md +++ b/lessons/javascript/stage-3/level-6/lesson.md @@ -51,14 +51,14 @@ Search Algorithms - Design an algorithm to solve this problem, then implement it ### How to Run 1. **Run the code**: - ```bash + ``` node hello.js - ```java + ``` **Expected output:** -```javascript +``` Hello, World! -```javascript +``` ### How to Approach This @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```javascript +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -169,7 +169,7 @@ BEGIN - Step 3 4. Display results END -```javascript +``` Then translate this directly to Javascript code. @@ -212,40 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```js -console.log("Hello, World!"); - -```js - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard javascript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/javascript/stage-3/level-7/lesson.md b/lessons/javascript/stage-3/level-7/lesson.md index aaad8d6..d1633a7 100644 --- a/lessons/javascript/stage-3/level-7/lesson.md +++ b/lessons/javascript/stage-3/level-7/lesson.md @@ -51,14 +51,14 @@ Sorting Algorithms - Design an algorithm to solve this problem, then implement i ### How to Run 1. **Run the code**: - ```bash + ``` node hello.js - ```java + ``` **Expected output:** -```javascript +``` Hello, World! -```javascript +``` ### How to Approach This @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```javascript +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -169,7 +169,7 @@ BEGIN - Step 3 4. Display results END -```javascript +``` Then translate this directly to Javascript code. @@ -212,40 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```js -console.log("Hello, World!"); - -```js - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard javascript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/javascript/stage-4/level-1/lesson.md b/lessons/javascript/stage-4/level-1/lesson.md index 881572e..8d312ce 100644 --- a/lessons/javascript/stage-4/level-1/lesson.md +++ b/lessons/javascript/stage-4/level-1/lesson.md @@ -51,14 +51,14 @@ Build a complete Calculator Application application that: ### How to Run 1. **Run the code**: - ```bash + ``` node hello.js - ```java + ``` **Expected output:** -```javascript +``` Hello, World! -```javascript +``` ### How to Approach This @@ -158,13 +158,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```javascript +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```javascript +``` Build incrementally - get one feature working before adding the next. @@ -207,40 +207,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```js -console.log("Hello, World!"); - -```js - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard javascript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/javascript/stage-4/level-2/lesson.md b/lessons/javascript/stage-4/level-2/lesson.md index 4d28e79..cad9146 100644 --- a/lessons/javascript/stage-4/level-2/lesson.md +++ b/lessons/javascript/stage-4/level-2/lesson.md @@ -51,14 +51,14 @@ Build a complete Text Analysis Tool application that: ### How to Run 1. **Run the code**: - ```bash + ``` node hello.js - ```java + ``` **Expected output:** -```javascript +``` Hello, World! -```javascript +``` ### How to Approach This @@ -158,13 +158,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```javascript +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```javascript +``` Build incrementally - get one feature working before adding the next. @@ -207,40 +207,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```js -console.log("Hello, World!"); - -```js - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard javascript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/javascript/stage-4/level-3/lesson.md b/lessons/javascript/stage-4/level-3/lesson.md index 8c745a2..0fb61ed 100644 --- a/lessons/javascript/stage-4/level-3/lesson.md +++ b/lessons/javascript/stage-4/level-3/lesson.md @@ -51,14 +51,14 @@ Build a complete Data Processing application that: ### How to Run 1. **Run the code**: - ```bash + ``` node hello.js - ```java + ``` **Expected output:** -```javascript +``` Hello, World! -```javascript +``` ### How to Approach This @@ -158,13 +158,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```javascript +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```javascript +``` Build incrementally - get one feature working before adding the next. @@ -207,40 +207,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```js -console.log("Hello, World!"); - -```js - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard javascript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/javascript/stage-4/level-4/lesson.md b/lessons/javascript/stage-4/level-4/lesson.md index 2751744..2fc2654 100644 --- a/lessons/javascript/stage-4/level-4/lesson.md +++ b/lessons/javascript/stage-4/level-4/lesson.md @@ -51,14 +51,14 @@ Build a complete File Operations application that: ### How to Run 1. **Run the code**: - ```bash + ``` node hello.js - ```java + ``` **Expected output:** -```javascript +``` Hello, World! -```javascript +``` ### How to Approach This @@ -158,13 +158,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```javascript +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```javascript +``` Build incrementally - get one feature working before adding the next. @@ -207,40 +207,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```js -console.log("Hello, World!"); - -```js - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard javascript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/javascript/stage-4/level-5/lesson.md b/lessons/javascript/stage-4/level-5/lesson.md index 2f86a04..4a48a13 100644 --- a/lessons/javascript/stage-4/level-5/lesson.md +++ b/lessons/javascript/stage-4/level-5/lesson.md @@ -51,14 +51,14 @@ Build a complete API Integration application that: ### How to Run 1. **Run the code**: - ```bash + ``` node hello.js - ```java + ``` **Expected output:** -```javascript +``` Hello, World! -```javascript +``` ### How to Approach This @@ -158,13 +158,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```javascript +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```javascript +``` Build incrementally - get one feature working before adding the next. @@ -207,40 +207,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```js -console.log("Hello, World!"); - -```js - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard javascript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/javascript/stage-4/level-6/lesson.md b/lessons/javascript/stage-4/level-6/lesson.md index 20005a9..429e38a 100644 --- a/lessons/javascript/stage-4/level-6/lesson.md +++ b/lessons/javascript/stage-4/level-6/lesson.md @@ -51,14 +51,14 @@ Build a complete Database Operations application that: ### How to Run 1. **Run the code**: - ```bash + ``` node hello.js - ```java + ``` **Expected output:** -```javascript +``` Hello, World! -```javascript +``` ### How to Approach This @@ -158,13 +158,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```javascript +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```javascript +``` Build incrementally - get one feature working before adding the next. @@ -207,40 +207,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```js -console.log("Hello, World!"); - -```js - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard javascript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/javascript/stage-4/level-7/lesson.md b/lessons/javascript/stage-4/level-7/lesson.md index b3e4d28..e8ea257 100644 --- a/lessons/javascript/stage-4/level-7/lesson.md +++ b/lessons/javascript/stage-4/level-7/lesson.md @@ -51,14 +51,14 @@ Build a complete Complete Application application that: ### How to Run 1. **Run the code**: - ```bash + ``` node hello.js - ```java + ``` **Expected output:** -```javascript +``` Hello, World! -```javascript +``` ### How to Approach This @@ -158,13 +158,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```javascript +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```javascript +``` Build incrementally - get one feature working before adding the next. @@ -207,40 +207,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```js -console.log("Hello, World!"); - -```js - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard javascript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/javascript/stage-5/level-1/lesson.md b/lessons/javascript/stage-5/level-1/lesson.md index 690037d..f3d9bcf 100644 --- a/lessons/javascript/stage-5/level-1/lesson.md +++ b/lessons/javascript/stage-5/level-1/lesson.md @@ -58,14 +58,14 @@ Create a production-ready Web Scraper using Javascript with: ### How to Run 1. **Run the code**: - ```bash + ``` node hello.js - ```java + ``` **Expected output:** -```javascript +``` Hello, World! -```javascript +``` ### How to Approach This @@ -222,40 +222,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```js -console.log("Hello, World!"); - -```js - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard javascript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/javascript/stage-5/level-2/lesson.md b/lessons/javascript/stage-5/level-2/lesson.md index 094b5f0..175ec2a 100644 --- a/lessons/javascript/stage-5/level-2/lesson.md +++ b/lessons/javascript/stage-5/level-2/lesson.md @@ -58,14 +58,14 @@ Create a production-ready CLI Tool using Javascript with: ### How to Run 1. **Run the code**: - ```bash + ``` node hello.js - ```java + ``` **Expected output:** -```javascript +``` Hello, World! -```javascript +``` ### How to Approach This @@ -222,40 +222,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```js -console.log("Hello, World!"); - -```js - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard javascript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/javascript/stage-5/level-3/lesson.md b/lessons/javascript/stage-5/level-3/lesson.md index 23639df..9ef2b3a 100644 --- a/lessons/javascript/stage-5/level-3/lesson.md +++ b/lessons/javascript/stage-5/level-3/lesson.md @@ -58,14 +58,14 @@ Create a production-ready REST API using Javascript with: ### How to Run 1. **Run the code**: - ```bash + ``` node hello.js - ```java + ``` **Expected output:** -```javascript +``` Hello, World! -```javascript +``` ### How to Approach This @@ -222,40 +222,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```js -console.log("Hello, World!"); - -```js - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard javascript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/javascript/stage-5/level-4/lesson.md b/lessons/javascript/stage-5/level-4/lesson.md index f8e5125..ceda04b 100644 --- a/lessons/javascript/stage-5/level-4/lesson.md +++ b/lessons/javascript/stage-5/level-4/lesson.md @@ -58,14 +58,14 @@ Create a production-ready Data Visualization using Javascript with: ### How to Run 1. **Run the code**: - ```bash + ``` node hello.js - ```java + ``` **Expected output:** -```javascript +``` Hello, World! -```javascript +``` ### How to Approach This @@ -222,40 +222,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```js -console.log("Hello, World!"); - -```js - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard javascript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/javascript/stage-5/level-5/lesson.md b/lessons/javascript/stage-5/level-5/lesson.md index ecf5963..3aed2c5 100644 --- a/lessons/javascript/stage-5/level-5/lesson.md +++ b/lessons/javascript/stage-5/level-5/lesson.md @@ -58,14 +58,14 @@ Create a production-ready Automated Testing using Javascript with: ### How to Run 1. **Run the code**: - ```bash + ``` node hello.js - ```java + ``` **Expected output:** -```javascript +``` Hello, World! -```javascript +``` ### How to Approach This @@ -222,40 +222,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```js -console.log("Hello, World!"); - -```js - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard javascript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/javascript/stage-5/level-6/lesson.md b/lessons/javascript/stage-5/level-6/lesson.md index 83c9114..39d9669 100644 --- a/lessons/javascript/stage-5/level-6/lesson.md +++ b/lessons/javascript/stage-5/level-6/lesson.md @@ -58,14 +58,14 @@ Create a production-ready Performance Optimization using Javascript with: ### How to Run 1. **Run the code**: - ```bash + ``` node hello.js - ```java + ``` **Expected output:** -```javascript +``` Hello, World! -```javascript +``` ### How to Approach This @@ -222,40 +222,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```js -console.log("Hello, World!"); - -```js - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard javascript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/javascript/stage-5/level-7/lesson.md b/lessons/javascript/stage-5/level-7/lesson.md index 52e7444..7695aa4 100644 --- a/lessons/javascript/stage-5/level-7/lesson.md +++ b/lessons/javascript/stage-5/level-7/lesson.md @@ -58,14 +58,14 @@ Create a production-ready Final Capstone Project using Javascript with: ### How to Run 1. **Run the code**: - ```bash + ``` node hello.js - ```java + ``` **Expected output:** -```javascript +``` Hello, World! -```javascript +``` ### How to Approach This @@ -222,40 +222,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```js -console.log("Hello, World!"); - -```js - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard javascript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/julia/stage-1/level-1/lesson.md b/lessons/julia/stage-1/level-1/lesson.md index 30ec593..bd4f126 100644 --- a/lessons/julia/stage-1/level-1/lesson.md +++ b/lessons/julia/stage-1/level-1/lesson.md @@ -23,28 +23,28 @@ Welcome to your first Julia program! Today, you'll create and run your very firs **Copy the following code EXACTLY as shown below into `main.jl`** -```julia +``` println("Hello, World!") -```julia +``` --- ### How to Run **Method 1 (Vim - Recommended):** -```julia +``` r -```julia +``` **Method 2 (Terminal):** -```bash +``` julia main.jl -```julia +``` **Expected output:** -```julia +``` Hello, World! -```julia +``` --- @@ -91,44 +91,24 @@ You just created a real Julia program! Here's what makes it work: --- -## ANSWER KEY (No peeking until you've tried!) +## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -The code you copied demonstrates fundamental Julia concepts: - -**Key Components:** -- Syntax rules specific to Julia -- How data is stored and manipulated -- Input/output operations -- Program flow and structure - -### Common Errors & Solutions - -| Error | Cause | Solution | -|-------|-------|----------| -| Syntax error | Typo in code | Double-check spelling and punctuation | -| Runtime error | Code runs but crashes | Check your logic and data types | -| Unexpected output | Logic error | Review your algorithm step-by-step | +``` +println("Hello, World!") +``` -### Bonus Knowledge +### Explanation -- Julia has a rich ecosystem of libraries and tools -- Understanding these basics prepares you for advanced topics -- Practice is key - try writing similar programs from scratch -- Every expert programmer started exactly where you are now! +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -### Real-World Applications +### Success Criteria -This concept is used in: -1. Professional software development -2. Web applications and mobile apps -3. Data analysis and scientific computing -4. Automation and scripting -5. Game development +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -**Excellent work! You've mastered a fundamental concept!** - -*Ready for the next challenge? Keep going!* +**Great job! You've completed this lesson!** diff --git a/lessons/julia/stage-1/level-2/lesson.md b/lessons/julia/stage-1/level-2/lesson.md index 77d1d7f..9a9ba13 100644 --- a/lessons/julia/stage-1/level-2/lesson.md +++ b/lessons/julia/stage-1/level-2/lesson.md @@ -23,7 +23,7 @@ Learn how to store and work with different types of data in Julia. **Copy the following code EXACTLY as shown below into `main.jl`** -```julia +``` # Numeric variables age = 25 score = 100 @@ -36,28 +36,28 @@ name = "Alex" println("Name: $name") println("Age: $age") println("Price: \$", @sprintf("%.2f", price)) -```julia +``` --- ### How to Run **Method 1 (Vim - Recommended):** -```julia +``` r -```julia +``` **Method 2 (Terminal):** -```bash +``` julia main.jl -```julia +``` **Expected output:** -```julia +``` Name: Alex Age: 25 Price: $29.99 -```julia +``` --- @@ -104,44 +104,35 @@ You just created a real Julia program! Here's what makes it work: --- -## ANSWER KEY (No peeking until you've tried!) +## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -The code you copied demonstrates fundamental Julia concepts: - -**Key Components:** -- Syntax rules specific to Julia -- How data is stored and manipulated -- Input/output operations -- Program flow and structure +``` +# Numeric variables +age = 25 +score = 100 +price = 29.99 -### Common Errors & Solutions +# String variable +name = "Alex" -| Error | Cause | Solution | -|-------|-------|----------| -| Syntax error | Typo in code | Double-check spelling and punctuation | -| Runtime error | Code runs but crashes | Check your logic and data types | -| Unexpected output | Logic error | Review your algorithm step-by-step | +# Display +println("Name: $name") +println("Age: $age") +println("Price: \$", @sprintf("%.2f", price)) +``` -### Bonus Knowledge +### Explanation -- Julia has a rich ecosystem of libraries and tools -- Understanding these basics prepares you for advanced topics -- Practice is key - try writing similar programs from scratch -- Every expert programmer started exactly where you are now! +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -### Real-World Applications +### Success Criteria -This concept is used in: -1. Professional software development -2. Web applications and mobile apps -3. Data analysis and scientific computing -4. Automation and scripting -5. Game development +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -**Excellent work! You've mastered a fundamental concept!** - -*Ready for the next challenge? Keep going!* +**Great job! You've completed this lesson!** diff --git a/lessons/julia/stage-1/level-3/lesson.md b/lessons/julia/stage-1/level-3/lesson.md index 889b3f6..e140bb2 100644 --- a/lessons/julia/stage-1/level-3/lesson.md +++ b/lessons/julia/stage-1/level-3/lesson.md @@ -23,7 +23,7 @@ Master arithmetic operations and use Julia as your powerful calculator. **Copy the following code EXACTLY as shown below into `main.jl`** -```julia +``` a = 10 b = 3 @@ -33,29 +33,29 @@ println("Multiplication: ", a * b) println("Division: ", a / b) println("Integer division: ", a ÷ b) println("Modulus: ", a % b) -```julia +``` --- ### How to Run **Method 1 (Vim - Recommended):** -```julia +``` r -```julia +``` **Method 2 (Terminal):** -```bash +``` julia main.jl -```julia +``` **Expected output:** -```julia +``` Sum: 13 Difference: 7 Product: 30 Quotient: 3.33 -```julia +``` --- @@ -102,44 +102,32 @@ You just created a real Julia program! Here's what makes it work: --- -## ANSWER KEY (No peeking until you've tried!) +## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -The code you copied demonstrates fundamental Julia concepts: - -**Key Components:** -- Syntax rules specific to Julia -- How data is stored and manipulated -- Input/output operations -- Program flow and structure - -### Common Errors & Solutions +``` +a = 10 +b = 3 -| Error | Cause | Solution | -|-------|-------|----------| -| Syntax error | Typo in code | Double-check spelling and punctuation | -| Runtime error | Code runs but crashes | Check your logic and data types | -| Unexpected output | Logic error | Review your algorithm step-by-step | +println("Addition: ", a + b) +println("Subtraction: ", a - b) +println("Multiplication: ", a * b) +println("Division: ", a / b) +println("Integer division: ", a ÷ b) +println("Modulus: ", a % b) +``` -### Bonus Knowledge +### Explanation -- Julia has a rich ecosystem of libraries and tools -- Understanding these basics prepares you for advanced topics -- Practice is key - try writing similar programs from scratch -- Every expert programmer started exactly where you are now! +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -### Real-World Applications +### Success Criteria -This concept is used in: -1. Professional software development -2. Web applications and mobile apps -3. Data analysis and scientific computing -4. Automation and scripting -5. Game development +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -**Excellent work! You've mastered a fundamental concept!** - -*Ready for the next challenge? Keep going!* +**Great job! You've completed this lesson!** diff --git a/lessons/julia/stage-1/level-4/lesson.md b/lessons/julia/stage-1/level-4/lesson.md index f3ae38b..901c839 100644 --- a/lessons/julia/stage-1/level-4/lesson.md +++ b/lessons/julia/stage-1/level-4/lesson.md @@ -23,7 +23,7 @@ Make your programs interactive by reading input from users. **Copy the following code EXACTLY as shown below into `main.jl`** -```julia +``` print("Enter your name: ") name = readline() @@ -32,26 +32,26 @@ age = parse(Int, readline()) println("Hello, $name!") println("You are $age years old.") -```julia +``` --- ### How to Run **Method 1 (Vim - Recommended):** -```julia +``` r -```julia +``` **Method 2 (Terminal):** -```bash +``` julia main.jl -```julia +``` **Expected output:** -```julia +``` [Interactive - output varies based on user input] -```julia +``` --- @@ -98,44 +98,31 @@ You just created a real Julia program! Here's what makes it work: --- -## ANSWER KEY (No peeking until you've tried!) +## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -The code you copied demonstrates fundamental Julia concepts: - -**Key Components:** -- Syntax rules specific to Julia -- How data is stored and manipulated -- Input/output operations -- Program flow and structure +``` +print("Enter your name: ") +name = readline() -### Common Errors & Solutions +print("Enter your age: ") +age = parse(Int, readline()) -| Error | Cause | Solution | -|-------|-------|----------| -| Syntax error | Typo in code | Double-check spelling and punctuation | -| Runtime error | Code runs but crashes | Check your logic and data types | -| Unexpected output | Logic error | Review your algorithm step-by-step | +println("Hello, $name!") +println("You are $age years old.") +``` -### Bonus Knowledge +### Explanation -- Julia has a rich ecosystem of libraries and tools -- Understanding these basics prepares you for advanced topics -- Practice is key - try writing similar programs from scratch -- Every expert programmer started exactly where you are now! +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -### Real-World Applications +### Success Criteria -This concept is used in: -1. Professional software development -2. Web applications and mobile apps -3. Data analysis and scientific computing -4. Automation and scripting -5. Game development +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -**Excellent work! You've mastered a fundamental concept!** - -*Ready for the next challenge? Keep going!* +**Great job! You've completed this lesson!** diff --git a/lessons/julia/stage-1/level-5/lesson.md b/lessons/julia/stage-1/level-5/lesson.md index 1deafbb..62924c0 100644 --- a/lessons/julia/stage-1/level-5/lesson.md +++ b/lessons/julia/stage-1/level-5/lesson.md @@ -23,7 +23,7 @@ Add decision-making to your programs with if/else statements. **Copy the following code EXACTLY as shown below into `main.jl`** -```julia +``` print("Enter your score (0-100): ") score = parse(Int, readline()) @@ -38,26 +38,26 @@ elseif score >= 60 else println("Grade: F - Study harder!") end -```julia +``` --- ### How to Run **Method 1 (Vim - Recommended):** -```julia +``` r -```julia +``` **Method 2 (Terminal):** -```bash +``` julia main.jl -```julia +``` **Expected output:** -```julia +``` [Output depends on conditions - varies based on input] -```julia +``` --- @@ -104,44 +104,37 @@ You just created a real Julia program! Here's what makes it work: --- -## ANSWER KEY (No peeking until you've tried!) +## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -The code you copied demonstrates fundamental Julia concepts: - -**Key Components:** -- Syntax rules specific to Julia -- How data is stored and manipulated -- Input/output operations -- Program flow and structure - -### Common Errors & Solutions +``` +print("Enter your score (0-100): ") +score = parse(Int, readline()) -| Error | Cause | Solution | -|-------|-------|----------| -| Syntax error | Typo in code | Double-check spelling and punctuation | -| Runtime error | Code runs but crashes | Check your logic and data types | -| Unexpected output | Logic error | Review your algorithm step-by-step | +if score >= 90 + println("Grade: A - Excellent!") +elseif score >= 80 + println("Grade: B - Good job!") +elseif score >= 70 + println("Grade: C - Passing") +elseif score >= 60 + println("Grade: D - Needs improvement") +else + println("Grade: F - Study harder!") +end +``` -### Bonus Knowledge +### Explanation -- Julia has a rich ecosystem of libraries and tools -- Understanding these basics prepares you for advanced topics -- Practice is key - try writing similar programs from scratch -- Every expert programmer started exactly where you are now! +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -### Real-World Applications +### Success Criteria -This concept is used in: -1. Professional software development -2. Web applications and mobile apps -3. Data analysis and scientific computing -4. Automation and scripting -5. Game development +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -**Excellent work! You've mastered a fundamental concept!** - -*Ready for the next challenge? Keep going!* +**Great job! You've completed this lesson!** diff --git a/lessons/julia/stage-1/level-6/lesson.md b/lessons/julia/stage-1/level-6/lesson.md index 2d5c853..6c02f67 100644 --- a/lessons/julia/stage-1/level-6/lesson.md +++ b/lessons/julia/stage-1/level-6/lesson.md @@ -23,7 +23,7 @@ Learn to repeat actions efficiently using loops. **Copy the following code EXACTLY as shown below into `main.jl`** -```julia +``` # For loop println("Counting 1 to 10:") for i in 1:10 @@ -46,26 +46,26 @@ println("\n$num times table:") for i in 1:10 println("$num × $i = $(num * i)") end -```julia +``` --- ### How to Run **Method 1 (Vim - Recommended):** -```julia +``` r -```julia +``` **Method 2 (Terminal):** -```bash +``` julia main.jl -```julia +``` **Expected output:** -```julia +``` 1 2 3 4 5 6 7 8 9 10 -```julia +``` --- @@ -112,44 +112,45 @@ You just created a real Julia program! Here's what makes it work: --- -## ANSWER KEY (No peeking until you've tried!) +## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -The code you copied demonstrates fundamental Julia concepts: - -**Key Components:** -- Syntax rules specific to Julia -- How data is stored and manipulated -- Input/output operations -- Program flow and structure +``` +# For loop +println("Counting 1 to 10:") +for i in 1:10 + print("$i ") +end +println() -### Common Errors & Solutions +# While loop +println("\nCountdown:") +count = 5 +while count > 0 + println(count) + count -= 1 +end +println("Blastoff!") -| Error | Cause | Solution | -|-------|-------|----------| -| Syntax error | Typo in code | Double-check spelling and punctuation | -| Runtime error | Code runs but crashes | Check your logic and data types | -| Unexpected output | Logic error | Review your algorithm step-by-step | +# Multiplication table +num = 7 +println("\n$num times table:") +for i in 1:10 + println("$num × $i = $(num * i)") +end +``` -### Bonus Knowledge +### Explanation -- Julia has a rich ecosystem of libraries and tools -- Understanding these basics prepares you for advanced topics -- Practice is key - try writing similar programs from scratch -- Every expert programmer started exactly where you are now! +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -### Real-World Applications +### Success Criteria -This concept is used in: -1. Professional software development -2. Web applications and mobile apps -3. Data analysis and scientific computing -4. Automation and scripting -5. Game development +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -**Excellent work! You've mastered a fundamental concept!** - -*Ready for the next challenge? Keep going!* +**Great job! You've completed this lesson!** diff --git a/lessons/julia/stage-1/level-7/lesson.md b/lessons/julia/stage-1/level-7/lesson.md index 49af3e4..739e438 100644 --- a/lessons/julia/stage-1/level-7/lesson.md +++ b/lessons/julia/stage-1/level-7/lesson.md @@ -23,7 +23,7 @@ Organize your code into reusable functions/methods. **Copy the following code EXACTLY as shown below into `main.jl`** -```julia +``` # Function to greet someone function greet(name) println("Hello, $name!") @@ -50,26 +50,26 @@ sum_result = add(5, 3) println("5 + 3 = $sum_result") println("5! = $(factorial_calc(5))") -```julia +``` --- ### How to Run **Method 1 (Vim - Recommended):** -```julia +``` r -```julia +``` **Method 2 (Terminal):** -```bash +``` julia main.jl -```julia +``` **Expected output:** -```julia +``` Result: 15 -```julia +``` --- @@ -116,44 +116,49 @@ You just created a real Julia program! Here's what makes it work: --- -## ANSWER KEY (No peeking until you've tried!) +## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -The code you copied demonstrates fundamental Julia concepts: +``` +# Function to greet someone +function greet(name) + println("Hello, $name!") +end + +# Function that returns a value +function add(a, b) + return a + b +end + +# Function to calculate factorial +function factorial_calc(n) + result = 1 + for i in 1:n + result *= i + end + return result +end -**Key Components:** -- Syntax rules specific to Julia -- How data is stored and manipulated -- Input/output operations -- Program flow and structure +greet("Alice") +greet("Bob") -### Common Errors & Solutions +sum_result = add(5, 3) +println("5 + 3 = $sum_result") -| Error | Cause | Solution | -|-------|-------|----------| -| Syntax error | Typo in code | Double-check spelling and punctuation | -| Runtime error | Code runs but crashes | Check your logic and data types | -| Unexpected output | Logic error | Review your algorithm step-by-step | +println("5! = $(factorial_calc(5))") +``` -### Bonus Knowledge +### Explanation -- Julia has a rich ecosystem of libraries and tools -- Understanding these basics prepares you for advanced topics -- Practice is key - try writing similar programs from scratch -- Every expert programmer started exactly where you are now! +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -### Real-World Applications +### Success Criteria -This concept is used in: -1. Professional software development -2. Web applications and mobile apps -3. Data analysis and scientific computing -4. Automation and scripting -5. Game development +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -**Excellent work! You've mastered a fundamental concept!** - -*Ready for the next challenge? Keep going!* +**Great job! You've completed this lesson!** diff --git a/lessons/julia/stage-2/level-1/lesson.md b/lessons/julia/stage-2/level-1/lesson.md index eb8adeb..ba59a3a 100644 --- a/lessons/julia/stage-2/level-1/lesson.md +++ b/lessons/julia/stage-2/level-1/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Julia:** -```julia +``` ALGORITHM: Basic Algorithm Translation BEGIN @@ -39,7 +39,7 @@ BEGIN // Translate step by step into Julia // Test with sample inputs END -```julia +``` **Implementation Steps:** 1. Analyze what the algorithm does @@ -54,14 +54,14 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` julia hello.jl ``` **Expected output:** -```julia +``` Hello, World! -```julia +``` ### How to Approach This @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in Julia: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```julia +``` PSEUDOCODE: READ number IF number > 0 THEN @@ -168,7 +168,7 @@ PSEUDOCODE: ELSE PRINT "Not positive" END IF -```julia +``` This becomes structured Julia code following the language syntax. diff --git a/lessons/julia/stage-2/level-2/lesson.md b/lessons/julia/stage-2/level-2/lesson.md index 571f874..964951e 100644 --- a/lessons/julia/stage-2/level-2/lesson.md +++ b/lessons/julia/stage-2/level-2/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Julia:** -```julia +``` ALGORITHM: Variables in Algorithms BEGIN @@ -39,7 +39,7 @@ BEGIN // Translate step by step into Julia // Test with sample inputs END -```julia +``` **Implementation Steps:** 1. Analyze what the algorithm does @@ -54,14 +54,14 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` julia hello.jl ``` **Expected output:** -```julia +``` Hello, World! -```julia +``` ### How to Approach This @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in Julia: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```julia +``` PSEUDOCODE: READ number IF number > 0 THEN @@ -168,7 +168,7 @@ PSEUDOCODE: ELSE PRINT "Not positive" END IF -```julia +``` This becomes structured Julia code following the language syntax. diff --git a/lessons/julia/stage-2/level-3/lesson.md b/lessons/julia/stage-2/level-3/lesson.md index 67df984..4532ad8 100644 --- a/lessons/julia/stage-2/level-3/lesson.md +++ b/lessons/julia/stage-2/level-3/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Julia:** -```julia +``` ALGORITHM: Mathematical Algorithms BEGIN @@ -39,7 +39,7 @@ BEGIN // Translate step by step into Julia // Test with sample inputs END -```julia +``` **Implementation Steps:** 1. Analyze what the algorithm does @@ -54,14 +54,14 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` julia hello.jl ``` **Expected output:** -```julia +``` Hello, World! -```julia +``` ### How to Approach This @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in Julia: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```julia +``` PSEUDOCODE: READ number IF number > 0 THEN @@ -168,7 +168,7 @@ PSEUDOCODE: ELSE PRINT "Not positive" END IF -```julia +``` This becomes structured Julia code following the language syntax. diff --git a/lessons/julia/stage-2/level-4/lesson.md b/lessons/julia/stage-2/level-4/lesson.md index ad97132..12f4320 100644 --- a/lessons/julia/stage-2/level-4/lesson.md +++ b/lessons/julia/stage-2/level-4/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Julia:** -```julia +``` ALGORITHM: Input/Output Algorithms BEGIN @@ -39,7 +39,7 @@ BEGIN // Translate step by step into Julia // Test with sample inputs END -```julia +``` **Implementation Steps:** 1. Analyze what the algorithm does @@ -54,14 +54,14 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` julia hello.jl ``` **Expected output:** -```julia +``` Hello, World! -```julia +``` ### How to Approach This @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in Julia: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```julia +``` PSEUDOCODE: READ number IF number > 0 THEN @@ -168,7 +168,7 @@ PSEUDOCODE: ELSE PRINT "Not positive" END IF -```julia +``` This becomes structured Julia code following the language syntax. diff --git a/lessons/julia/stage-2/level-5/lesson.md b/lessons/julia/stage-2/level-5/lesson.md index f0b722c..1656055 100644 --- a/lessons/julia/stage-2/level-5/lesson.md +++ b/lessons/julia/stage-2/level-5/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Julia:** -```julia +``` ALGORITHM: Decision Algorithms BEGIN @@ -39,7 +39,7 @@ BEGIN // Translate step by step into Julia // Test with sample inputs END -```julia +``` **Implementation Steps:** 1. Analyze what the algorithm does @@ -54,14 +54,14 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` julia hello.jl ``` **Expected output:** -```julia +``` Hello, World! -```julia +``` ### How to Approach This @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in Julia: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```julia +``` PSEUDOCODE: READ number IF number > 0 THEN @@ -168,7 +168,7 @@ PSEUDOCODE: ELSE PRINT "Not positive" END IF -```julia +``` This becomes structured Julia code following the language syntax. diff --git a/lessons/julia/stage-2/level-6/lesson.md b/lessons/julia/stage-2/level-6/lesson.md index 2131996..9cfadf6 100644 --- a/lessons/julia/stage-2/level-6/lesson.md +++ b/lessons/julia/stage-2/level-6/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Julia:** -```julia +``` ALGORITHM: Loop Algorithms BEGIN @@ -39,7 +39,7 @@ BEGIN // Translate step by step into Julia // Test with sample inputs END -```julia +``` **Implementation Steps:** 1. Analyze what the algorithm does @@ -54,14 +54,14 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` julia hello.jl ``` **Expected output:** -```julia +``` Hello, World! -```julia +``` ### How to Approach This @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in Julia: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```julia +``` PSEUDOCODE: READ number IF number > 0 THEN @@ -168,7 +168,7 @@ PSEUDOCODE: ELSE PRINT "Not positive" END IF -```julia +``` This becomes structured Julia code following the language syntax. diff --git a/lessons/julia/stage-2/level-7/lesson.md b/lessons/julia/stage-2/level-7/lesson.md index 305787d..dc546b8 100644 --- a/lessons/julia/stage-2/level-7/lesson.md +++ b/lessons/julia/stage-2/level-7/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Julia:** -```julia +``` ALGORITHM: Function Design BEGIN @@ -39,7 +39,7 @@ BEGIN // Translate step by step into Julia // Test with sample inputs END -```julia +``` **Implementation Steps:** 1. Analyze what the algorithm does @@ -54,14 +54,14 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` julia hello.jl ``` **Expected output:** -```julia +``` Hello, World! -```julia +``` ### How to Approach This @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in Julia: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```julia +``` PSEUDOCODE: READ number IF number > 0 THEN @@ -168,7 +168,7 @@ PSEUDOCODE: ELSE PRINT "Not positive" END IF -```julia +``` This becomes structured Julia code following the language syntax. diff --git a/lessons/julia/stage-3/level-1/lesson.md b/lessons/julia/stage-3/level-1/lesson.md index 251fa97..a1fe683 100644 --- a/lessons/julia/stage-3/level-1/lesson.md +++ b/lessons/julia/stage-3/level-1/lesson.md @@ -51,14 +51,14 @@ Simple Problem Analysis - Design an algorithm to solve this problem, then implem ### How to Run 1. **Run the code**: - ```bash + ``` julia hello.jl ``` **Expected output:** -```julia +``` Hello, World! -```julia +``` ### How to Approach This @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```julia +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -169,7 +169,7 @@ BEGIN - Step 3 4. Display results END -```julia +``` Then translate this directly to Julia code. diff --git a/lessons/julia/stage-3/level-2/lesson.md b/lessons/julia/stage-3/level-2/lesson.md index 022c351..a1adad0 100644 --- a/lessons/julia/stage-3/level-2/lesson.md +++ b/lessons/julia/stage-3/level-2/lesson.md @@ -51,14 +51,14 @@ Data Structure Planning - Design an algorithm to solve this problem, then implem ### How to Run 1. **Run the code**: - ```bash + ``` julia hello.jl ``` **Expected output:** -```julia +``` Hello, World! -```julia +``` ### How to Approach This @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```julia +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -169,7 +169,7 @@ BEGIN - Step 3 4. Display results END -```julia +``` Then translate this directly to Julia code. diff --git a/lessons/julia/stage-3/level-3/lesson.md b/lessons/julia/stage-3/level-3/lesson.md index 1b32f80..0e0a106 100644 --- a/lessons/julia/stage-3/level-3/lesson.md +++ b/lessons/julia/stage-3/level-3/lesson.md @@ -51,14 +51,14 @@ Mathematical Problems - Design an algorithm to solve this problem, then implemen ### How to Run 1. **Run the code**: - ```bash + ``` julia hello.jl ``` **Expected output:** -```julia +``` Hello, World! -```julia +``` ### How to Approach This @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```julia +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -169,7 +169,7 @@ BEGIN - Step 3 4. Display results END -```julia +``` Then translate this directly to Julia code. diff --git a/lessons/julia/stage-3/level-4/lesson.md b/lessons/julia/stage-3/level-4/lesson.md index 8947c07..37c2695 100644 --- a/lessons/julia/stage-3/level-4/lesson.md +++ b/lessons/julia/stage-3/level-4/lesson.md @@ -51,14 +51,14 @@ Text Processing Problems - Design an algorithm to solve this problem, then imple ### How to Run 1. **Run the code**: - ```bash + ``` julia hello.jl ``` **Expected output:** -```julia +``` Hello, World! -```julia +``` ### How to Approach This @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```julia +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -169,7 +169,7 @@ BEGIN - Step 3 4. Display results END -```julia +``` Then translate this directly to Julia code. diff --git a/lessons/julia/stage-3/level-5/lesson.md b/lessons/julia/stage-3/level-5/lesson.md index 77e5a33..a95a367 100644 --- a/lessons/julia/stage-3/level-5/lesson.md +++ b/lessons/julia/stage-3/level-5/lesson.md @@ -51,14 +51,14 @@ Logic Problems - Design an algorithm to solve this problem, then implement it. ### How to Run 1. **Run the code**: - ```bash + ``` julia hello.jl ``` **Expected output:** -```julia +``` Hello, World! -```julia +``` ### How to Approach This @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```julia +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -169,7 +169,7 @@ BEGIN - Step 3 4. Display results END -```julia +``` Then translate this directly to Julia code. diff --git a/lessons/julia/stage-3/level-6/lesson.md b/lessons/julia/stage-3/level-6/lesson.md index 0fef8a2..3bc49e2 100644 --- a/lessons/julia/stage-3/level-6/lesson.md +++ b/lessons/julia/stage-3/level-6/lesson.md @@ -51,14 +51,14 @@ Search Algorithms - Design an algorithm to solve this problem, then implement it ### How to Run 1. **Run the code**: - ```bash + ``` julia hello.jl ``` **Expected output:** -```julia +``` Hello, World! -```julia +``` ### How to Approach This @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```julia +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -169,7 +169,7 @@ BEGIN - Step 3 4. Display results END -```julia +``` Then translate this directly to Julia code. diff --git a/lessons/julia/stage-3/level-7/lesson.md b/lessons/julia/stage-3/level-7/lesson.md index 02e91c8..dc302c3 100644 --- a/lessons/julia/stage-3/level-7/lesson.md +++ b/lessons/julia/stage-3/level-7/lesson.md @@ -51,14 +51,14 @@ Sorting Algorithms - Design an algorithm to solve this problem, then implement i ### How to Run 1. **Run the code**: - ```bash + ``` julia hello.jl ``` **Expected output:** -```julia +``` Hello, World! -```julia +``` ### How to Approach This @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```julia +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -169,7 +169,7 @@ BEGIN - Step 3 4. Display results END -```julia +``` Then translate this directly to Julia code. diff --git a/lessons/julia/stage-4/level-1/lesson.md b/lessons/julia/stage-4/level-1/lesson.md index 00fd9d8..b06674e 100644 --- a/lessons/julia/stage-4/level-1/lesson.md +++ b/lessons/julia/stage-4/level-1/lesson.md @@ -51,14 +51,14 @@ Build a complete Calculator Application application that: ### How to Run 1. **Run the code**: - ```bash + ``` julia hello.jl ``` **Expected output:** -```julia +``` Hello, World! -```julia +``` ### How to Approach This @@ -158,13 +158,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```julia +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```julia +``` Build incrementally - get one feature working before adding the next. diff --git a/lessons/julia/stage-4/level-2/lesson.md b/lessons/julia/stage-4/level-2/lesson.md index 7bb8e04..edbd3f2 100644 --- a/lessons/julia/stage-4/level-2/lesson.md +++ b/lessons/julia/stage-4/level-2/lesson.md @@ -51,14 +51,14 @@ Build a complete Text Analysis Tool application that: ### How to Run 1. **Run the code**: - ```bash + ``` julia hello.jl ``` **Expected output:** -```julia +``` Hello, World! -```julia +``` ### How to Approach This @@ -158,13 +158,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```julia +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```julia +``` Build incrementally - get one feature working before adding the next. diff --git a/lessons/julia/stage-4/level-3/lesson.md b/lessons/julia/stage-4/level-3/lesson.md index 586714b..4528164 100644 --- a/lessons/julia/stage-4/level-3/lesson.md +++ b/lessons/julia/stage-4/level-3/lesson.md @@ -51,14 +51,14 @@ Build a complete Data Processing application that: ### How to Run 1. **Run the code**: - ```bash + ``` julia hello.jl ``` **Expected output:** -```julia +``` Hello, World! -```julia +``` ### How to Approach This @@ -158,13 +158,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```julia +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```julia +``` Build incrementally - get one feature working before adding the next. diff --git a/lessons/julia/stage-4/level-4/lesson.md b/lessons/julia/stage-4/level-4/lesson.md index 7baa595..769e177 100644 --- a/lessons/julia/stage-4/level-4/lesson.md +++ b/lessons/julia/stage-4/level-4/lesson.md @@ -51,14 +51,14 @@ Build a complete File Operations application that: ### How to Run 1. **Run the code**: - ```bash + ``` julia hello.jl ``` **Expected output:** -```julia +``` Hello, World! -```julia +``` ### How to Approach This @@ -158,13 +158,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```julia +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```julia +``` Build incrementally - get one feature working before adding the next. diff --git a/lessons/julia/stage-4/level-5/lesson.md b/lessons/julia/stage-4/level-5/lesson.md index 7f7e0b5..c2aa7bf 100644 --- a/lessons/julia/stage-4/level-5/lesson.md +++ b/lessons/julia/stage-4/level-5/lesson.md @@ -51,14 +51,14 @@ Build a complete API Integration application that: ### How to Run 1. **Run the code**: - ```bash + ``` julia hello.jl ``` **Expected output:** -```julia +``` Hello, World! -```julia +``` ### How to Approach This @@ -158,13 +158,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```julia +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```julia +``` Build incrementally - get one feature working before adding the next. diff --git a/lessons/julia/stage-4/level-6/lesson.md b/lessons/julia/stage-4/level-6/lesson.md index 5af6b3c..8cf39ec 100644 --- a/lessons/julia/stage-4/level-6/lesson.md +++ b/lessons/julia/stage-4/level-6/lesson.md @@ -51,14 +51,14 @@ Build a complete Database Operations application that: ### How to Run 1. **Run the code**: - ```bash + ``` julia hello.jl ``` **Expected output:** -```julia +``` Hello, World! -```julia +``` ### How to Approach This @@ -158,13 +158,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```julia +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```julia +``` Build incrementally - get one feature working before adding the next. diff --git a/lessons/julia/stage-4/level-7/lesson.md b/lessons/julia/stage-4/level-7/lesson.md index 98d98d7..7f99683 100644 --- a/lessons/julia/stage-4/level-7/lesson.md +++ b/lessons/julia/stage-4/level-7/lesson.md @@ -51,14 +51,14 @@ Build a complete Complete Application application that: ### How to Run 1. **Run the code**: - ```bash + ``` julia hello.jl ``` **Expected output:** -```julia +``` Hello, World! -```julia +``` ### How to Approach This @@ -158,13 +158,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```julia +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```julia +``` Build incrementally - get one feature working before adding the next. diff --git a/lessons/julia/stage-5/level-1/lesson.md b/lessons/julia/stage-5/level-1/lesson.md index 8163bc5..99e2abc 100644 --- a/lessons/julia/stage-5/level-1/lesson.md +++ b/lessons/julia/stage-5/level-1/lesson.md @@ -242,14 +242,14 @@ Follow these stages: **Your architecture will depend on your chosen project, but should include:** -```julia +``` // Main program structure // - Data definitions // - Core functions // - User interface // - File operations // - Main program loop -```julia +``` **Recommended Organization:** 1. Separate data structures from logic diff --git a/lessons/julia/stage-5/level-2/lesson.md b/lessons/julia/stage-5/level-2/lesson.md index 0bb68bf..2f9b4ed 100644 --- a/lessons/julia/stage-5/level-2/lesson.md +++ b/lessons/julia/stage-5/level-2/lesson.md @@ -233,14 +233,14 @@ Follow these stages: **Your architecture will depend on your chosen project, but should include:** -```julia +``` // Main program structure // - Data definitions // - Core functions // - User interface // - File operations // - Main program loop -```julia +``` **Recommended Organization:** 1. Separate data structures from logic diff --git a/lessons/julia/stage-5/level-3/lesson.md b/lessons/julia/stage-5/level-3/lesson.md index d4b6c2f..0a9ad6c 100644 --- a/lessons/julia/stage-5/level-3/lesson.md +++ b/lessons/julia/stage-5/level-3/lesson.md @@ -238,14 +238,14 @@ Follow these stages: **Your architecture will depend on your chosen project, but should include:** -```julia +``` // Main program structure // - Data definitions // - Core functions // - User interface // - File operations // - Main program loop -```julia +``` **Recommended Organization:** 1. Separate data structures from logic diff --git a/lessons/julia/stage-5/level-4/lesson.md b/lessons/julia/stage-5/level-4/lesson.md index 3a24bb8..ea9a5f5 100644 --- a/lessons/julia/stage-5/level-4/lesson.md +++ b/lessons/julia/stage-5/level-4/lesson.md @@ -233,14 +233,14 @@ Follow these stages: **Your architecture will depend on your chosen project, but should include:** -```julia +``` // Main program structure // - Data definitions // - Core functions // - User interface // - File operations // - Main program loop -```julia +``` **Recommended Organization:** 1. Separate data structures from logic diff --git a/lessons/julia/stage-5/level-5/lesson.md b/lessons/julia/stage-5/level-5/lesson.md index c7404e1..1b16847 100644 --- a/lessons/julia/stage-5/level-5/lesson.md +++ b/lessons/julia/stage-5/level-5/lesson.md @@ -238,14 +238,14 @@ Follow these stages: **Your architecture will depend on your chosen project, but should include:** -```julia +``` // Main program structure // - Data definitions // - Core functions // - User interface // - File operations // - Main program loop -```julia +``` **Recommended Organization:** 1. Separate data structures from logic diff --git a/lessons/julia/stage-5/level-6/lesson.md b/lessons/julia/stage-5/level-6/lesson.md index 68ada76..10e1f88 100644 --- a/lessons/julia/stage-5/level-6/lesson.md +++ b/lessons/julia/stage-5/level-6/lesson.md @@ -232,14 +232,14 @@ Follow these stages: **Your architecture will depend on your chosen project, but should include:** -```julia +``` // Main program structure // - Data definitions // - Core functions // - User interface // - File operations // - Main program loop -```julia +``` **Recommended Organization:** 1. Separate data structures from logic diff --git a/lessons/julia/stage-5/level-7/lesson.md b/lessons/julia/stage-5/level-7/lesson.md index f872d3d..4d610a5 100644 --- a/lessons/julia/stage-5/level-7/lesson.md +++ b/lessons/julia/stage-5/level-7/lesson.md @@ -235,14 +235,14 @@ Follow these stages: **Your architecture will depend on your chosen project, but should include:** -```julia +``` // Main program structure // - Data definitions // - Core functions // - User interface // - File operations // - Main program loop -```julia +``` **Recommended Organization:** 1. Separate data structures from logic diff --git a/lessons/kotlin/stage-1/level-1/lesson.md b/lessons/kotlin/stage-1/level-1/lesson.md index 1b47867..d7f050a 100644 --- a/lessons/kotlin/stage-1/level-1/lesson.md +++ b/lessons/kotlin/stage-1/level-1/lesson.md @@ -21,24 +21,24 @@ Welcome to Kotlin! Today, you'll create your first Kotlin program. Kotlin is a m Copy the following code EXACTLY as shown into a new file called `hello.kt`: -```kotlin +``` fun main() { println("Hello, World!") } -```kotlin +``` ### How to Execute -```bash +``` kotlinc hello.kt -include-runtime -d hello.jar java -jar hello.jar -```kotlin +``` Expected output: -```kotlin +``` Hello, World! -```kotlin +``` ### Success Checklist @@ -59,81 +59,24 @@ Hello, World! ## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown - -### Key Concepts - -- Review the code structure specific to Kotlin -- Understand the execution flow -- Learn common pitfalls and solutions - -### Next Steps - -Practice the code and experiment with variations! - ---- - -**Congratulations! Keep coding!** - - -### How to Run - -1. Open the code file -2. Review and understand the implementation -3. Execute using: `r` in Vim - +### Solution -### Additional Content - -Understand the key concepts: - -- Review each function -- Understand the flow -- Learn the patterns used - - -### Code Review - -Key functions and their purpose: - -- Main function: Entry point -- Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```kt +``` fun main() { println("Hello, World!") } - ``` -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: +### Explanation -1. **Structure**: The program follows standard kotlin conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -### Testing Your Solution +### Success Criteria -Try these test cases to verify your code works correctly: +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding +--- -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs +**Great job! You've completed this lesson!** diff --git a/lessons/kotlin/stage-1/level-2/lesson.md b/lessons/kotlin/stage-1/level-2/lesson.md index 77327af..67276f9 100644 --- a/lessons/kotlin/stage-1/level-2/lesson.md +++ b/lessons/kotlin/stage-1/level-2/lesson.md @@ -32,22 +32,22 @@ fun main() { println("Your height is $height feet.") println("Student status: $isStudent") } -```kotlin +``` ### How to Execute -```bash +``` kotlinc variables.kt -```kotlin +``` Expected output: -```kotlin +``` Hello, Alice! You are 25 years old. Your height is 5.6 feet. Student status: true -```kotlin +``` ### Success Checklist @@ -87,82 +87,32 @@ Remember to check the `VIM_CHEATSHEET.md` in the root directory for basic Vim co ## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown - -### Key Concepts - -- Review the code structure specific to Kotlin -- Understand the execution flow -- Learn common pitfalls and solutions - -### Next Steps - -Practice the code and experiment with variations! - ---- - -**Congratulations! Keep coding!** - - - -### How to Run - -1. Open the code file -2. Review and understand the implementation -3. Execute using: `r` in Vim - - -### Additional Content - -Understand the key concepts: - -- Review each function -- Understand the flow -- Learn the patterns used - - -### Code Review - -Key functions and their purpose: - -- Main function: Entry point -- Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution +### Solution ```kt fun main() { - println("Hello, World!") -} + val name = "Alice" + val age = 25 + val height = 5.6 + val isStudent = true + println("Hello, $name!") + println("You are $age years old.") + println("Your height is $height feet.") + println("Student status: $isStudent") +} ``` -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: +### Explanation -1. **Structure**: The program follows standard kotlin conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -### Testing Your Solution +### Success Criteria -Try these test cases to verify your code works correctly: +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding +--- -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs +**Great job! You've completed this lesson!** diff --git a/lessons/kotlin/stage-1/level-3/lesson.md b/lessons/kotlin/stage-1/level-3/lesson.md index ef07dab..49c61a7 100644 --- a/lessons/kotlin/stage-1/level-3/lesson.md +++ b/lessons/kotlin/stage-1/level-3/lesson.md @@ -23,22 +23,22 @@ Master arithmetic operations and use the language as your calculator. **Copy the following code EXACTLY as shown below into `main.kt`** -```kotlin +``` fun main() { val a = 15 val b = 4 - + println("Addition: $a + $b = ${a + b}") println("Subtraction: $a - $b = ${a - b}") println("Multiplication: $a × $b = ${a * b}") println("Division: $a / $b = ${a / b}") println("Remainder: $a % $b = ${a % b}") - + val x = 15.0 val y = 4.0 println("Precise Division: $x / $y = ${x / y}") } -```kotlin +``` --- @@ -60,22 +60,22 @@ fun main() { ### The Complete Code -```kotlin +``` fun main() { val a = 15 val b = 4 - + println("Addition: $a + $b = ${a + b}") println("Subtraction: $a - $b = ${a - b}") println("Multiplication: $a × $b = ${a * b}") println("Division: $a / $b = ${a / b}") println("Remainder: $a % $b = ${a % b}") - + val x = 15.0 val y = 4.0 println("Precise Division: $x / $y = ${x / y}") } -```kotlin +``` ### What This Code Does @@ -144,42 +144,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```kt -fun main() { - println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard kotlin conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/kotlin/stage-1/level-4/lesson.md b/lessons/kotlin/stage-1/level-4/lesson.md index d1190e5..3fc8544 100644 --- a/lessons/kotlin/stage-1/level-4/lesson.md +++ b/lessons/kotlin/stage-1/level-4/lesson.md @@ -23,19 +23,19 @@ Make your programs interactive by reading input from users. **Copy the following code EXACTLY as shown below into `main.kt`** -```kotlin +``` fun main() { print("Enter your name: ") val name = readLine() - + print("Enter your age: ") val age = readLine()!!.toInt() - + println("Hello, $name!") println("You are $age years old.") println("Next year you'll be ${age + 1}.") } -```kotlin +``` --- @@ -57,19 +57,19 @@ fun main() { ### The Complete Code -```kotlin +``` fun main() { print("Enter your name: ") val name = readLine() - + print("Enter your age: ") val age = readLine()!!.toInt() - + println("Hello, $name!") println("You are $age years old.") println("Next year you'll be ${age + 1}.") } -```kotlin +``` ### What This Code Does @@ -138,42 +138,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```kt -fun main() { - println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard kotlin conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/kotlin/stage-1/level-5/lesson.md b/lessons/kotlin/stage-1/level-5/lesson.md index bb7d03c..816753b 100644 --- a/lessons/kotlin/stage-1/level-5/lesson.md +++ b/lessons/kotlin/stage-1/level-5/lesson.md @@ -23,11 +23,11 @@ Add decision-making to your programs with if/else statements. **Copy the following code EXACTLY as shown below into `main.kt`** -```kotlin +``` fun main() { print("Enter a number: ") val num = readLine()!!.toInt() - + if (num > 0) { println("$num is positive") } else if (num < 0) { @@ -35,14 +35,14 @@ fun main() { } else { println("The number is zero") } - + if (num % 2 == 0) { println("$num is even") } else { println("$num is odd") } } -```kotlin +``` --- @@ -64,11 +64,11 @@ fun main() { ### The Complete Code -```kotlin +``` fun main() { print("Enter a number: ") val num = readLine()!!.toInt() - + if (num > 0) { println("$num is positive") } else if (num < 0) { @@ -76,14 +76,14 @@ fun main() { } else { println("The number is zero") } - + if (num % 2 == 0) { println("$num is even") } else { println("$num is odd") } } -```kotlin +``` ### What This Code Does @@ -150,42 +150,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```kt -fun main() { - println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard kotlin conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/kotlin/stage-1/level-6/lesson.md b/lessons/kotlin/stage-1/level-6/lesson.md index 00f204c..c1b6a4a 100644 --- a/lessons/kotlin/stage-1/level-6/lesson.md +++ b/lessons/kotlin/stage-1/level-6/lesson.md @@ -23,19 +23,19 @@ Learn to repeat actions efficiently using loops. **Copy the following code EXACTLY as shown below into `main.kt`** -```kotlin +``` fun main() { println("Counting 1 to 10:") for (i in 1..10) { print("$i ") } println() - + println("\nMultiplication table for 7:") for (i in 1..10) { println("7 × $i = ${7 * i}") } - + println("\nCountdown from 5:") var count = 5 while (count > 0) { @@ -44,7 +44,7 @@ fun main() { } println("Liftoff!") } -```kotlin +``` --- @@ -66,19 +66,19 @@ fun main() { ### The Complete Code -```kotlin +``` fun main() { println("Counting 1 to 10:") for (i in 1..10) { print("$i ") } println() - + println("\nMultiplication table for 7:") for (i in 1..10) { println("7 × $i = ${7 * i}") } - + println("\nCountdown from 5:") var count = 5 while (count > 0) { @@ -87,7 +87,7 @@ fun main() { } println("Liftoff!") } -```kotlin +``` ### What This Code Does @@ -153,42 +153,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```kt -fun main() { - println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard kotlin conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/kotlin/stage-1/level-7/lesson.md b/lessons/kotlin/stage-1/level-7/lesson.md index b9d6e93..90147e2 100644 --- a/lessons/kotlin/stage-1/level-7/lesson.md +++ b/lessons/kotlin/stage-1/level-7/lesson.md @@ -23,7 +23,7 @@ Organize your code into reusable functions/methods. **Copy the following code EXACTLY as shown below into `main.kt`** -```kotlin +``` fun greet(name: String) { println("Hello, $name!") } @@ -40,14 +40,14 @@ fun factorial(n: Int): Int { fun main() { greet("Alice") greet("Bob") - + val sum = add(15, 7) println("15 + 7 = $sum") - + val fact = factorial(5) println("5! = $fact") } -```kotlin +``` --- @@ -69,7 +69,7 @@ fun main() { ### The Complete Code -```kotlin +``` fun greet(name: String) { println("Hello, $name!") } @@ -86,14 +86,14 @@ fun factorial(n: Int): Int { fun main() { greet("Alice") greet("Bob") - + val sum = add(15, 7) println("15 + 7 = $sum") - + val fact = factorial(5) println("5! = $fact") } -```kotlin +``` ### What This Code Does @@ -162,42 +162,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```kt -fun main() { - println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard kotlin conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/kotlin/stage-2/level-1/lesson.md b/lessons/kotlin/stage-2/level-1/lesson.md index 2200929..beef5b0 100644 --- a/lessons/kotlin/stage-2/level-1/lesson.md +++ b/lessons/kotlin/stage-2/level-1/lesson.md @@ -20,13 +20,13 @@ Now that you know the basics, it's time to think like a programmer! You'll take Here's some pseudocode that describes a simple program: -```kotlin +``` START print "Welcome to the program!" print "This is my first real program" print "I'm learning to code!" END -```kotlin +``` **Your mission**: Translate this pseudocode into Kotlin code and save it as `main.kt`. @@ -38,18 +38,18 @@ Hints: ### How to Run -```bash +``` cd ~/.local/share/learn/workspaces/kotlin/stage-2/level-1 kotlinc main.kt -```kotlin +``` Expected output: -```kotlin +``` Welcome to the program! This is my first real program I'm learning to code! -```kotlin +``` ### Success Checklist @@ -69,53 +69,28 @@ If you're stuck, here's what your code should look like (don't peek until you tr --- -## ANSWER KEY +## ANSWER KEY (No cheating until you've tried!) -```kt -```kotlin +### Solution -(Fill in based on language-specific syntax) - -```kotlin - ---- - -## What's Different About Stage 2? - -**Stage 1 (Copying):** Code was provided, you typed it -**Stage 2 (Pseudocode→Code):** Logic is provided, you write the code - -This is a crucial step! You're now writing code from specifications, not just copying. This is how real programming works. - -### Key Concepts +``` +START + print "Welcome to the program!" + print "This is my first real program" + print "I'm learning to code!" +END +``` -- Pseudocode is language-independent - the same pseudocode could translate to many languages -- Your job is to understand the logic and implement it correctly -- Different languages have different syntax, but the logic is the same +### Explanation ---- +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -## Need Help with Vim? +### Success Criteria -Remember to check the `VIM_CHEATSHEET.md` in the root directory for basic Vim commands! +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -
- - -### Additional Content - -Understand the key concepts: - -- Review each function -- Understand the flow -- Learn the patterns used - - -### Code Review - -Key functions and their purpose: - -- Main function: Entry point -- Helper functions: Support logic +**Great job! You've completed this lesson!** diff --git a/lessons/kotlin/stage-2/level-2/lesson.md b/lessons/kotlin/stage-2/level-2/lesson.md index dbd9b37..9446f95 100644 --- a/lessons/kotlin/stage-2/level-2/lesson.md +++ b/lessons/kotlin/stage-2/level-2/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Kotlin:** -```kotlin +``` ALGORITHM: Variables in Algorithms BEGIN @@ -39,7 +39,7 @@ BEGIN // Translate step by step into Kotlin // Test with sample inputs END -```kotlin +``` **Implementation Steps:** 1. Analyze what the algorithm does @@ -54,19 +54,19 @@ END ### How to Run 1. **Compile the code**: - ```bash + ``` kotlinc hello.kt - ```kotlin + ``` 2. **Run your program**: - ```bash + ``` kotlin hello - ```kotlin + ``` **Expected output:** -```kotlin +``` Hello, World! -```kotlin +``` ### How to Approach This @@ -165,7 +165,7 @@ The key is understanding what each pseudocode statement represents in Kotlin: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```kotlin +``` PSEUDOCODE: READ number IF number > 0 THEN @@ -173,7 +173,7 @@ PSEUDOCODE: ELSE PRINT "Not positive" END IF -```kotlin +``` This becomes structured Kotlin code following the language syntax. @@ -216,42 +216,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```kt -fun main() { - println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard kotlin conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/kotlin/stage-2/level-3/lesson.md b/lessons/kotlin/stage-2/level-3/lesson.md index 1e17c7b..3781c6a 100644 --- a/lessons/kotlin/stage-2/level-3/lesson.md +++ b/lessons/kotlin/stage-2/level-3/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Kotlin:** -```kotlin +``` ALGORITHM: Mathematical Algorithms BEGIN @@ -39,7 +39,7 @@ BEGIN // Translate step by step into Kotlin // Test with sample inputs END -```kotlin +``` **Implementation Steps:** 1. Analyze what the algorithm does @@ -54,19 +54,19 @@ END ### How to Run 1. **Compile the code**: - ```bash + ``` kotlinc hello.kt - ```kotlin + ``` 2. **Run your program**: - ```bash + ``` kotlin hello - ```kotlin + ``` **Expected output:** -```kotlin +``` Hello, World! -```kotlin +``` ### How to Approach This @@ -165,7 +165,7 @@ The key is understanding what each pseudocode statement represents in Kotlin: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```kotlin +``` PSEUDOCODE: READ number IF number > 0 THEN @@ -173,7 +173,7 @@ PSEUDOCODE: ELSE PRINT "Not positive" END IF -```kotlin +``` This becomes structured Kotlin code following the language syntax. @@ -216,42 +216,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```kt -fun main() { - println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard kotlin conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/kotlin/stage-2/level-4/lesson.md b/lessons/kotlin/stage-2/level-4/lesson.md index 813d129..e4ab541 100644 --- a/lessons/kotlin/stage-2/level-4/lesson.md +++ b/lessons/kotlin/stage-2/level-4/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Kotlin:** -```kotlin +``` ALGORITHM: Input/Output Algorithms BEGIN @@ -39,7 +39,7 @@ BEGIN // Translate step by step into Kotlin // Test with sample inputs END -```kotlin +``` **Implementation Steps:** 1. Analyze what the algorithm does @@ -54,19 +54,19 @@ END ### How to Run 1. **Compile the code**: - ```bash + ``` kotlinc hello.kt - ```kotlin + ``` 2. **Run your program**: - ```bash + ``` kotlin hello - ```kotlin + ``` **Expected output:** -```kotlin +``` Hello, World! -```kotlin +``` ### How to Approach This @@ -165,7 +165,7 @@ The key is understanding what each pseudocode statement represents in Kotlin: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```kotlin +``` PSEUDOCODE: READ number IF number > 0 THEN @@ -173,7 +173,7 @@ PSEUDOCODE: ELSE PRINT "Not positive" END IF -```kotlin +``` This becomes structured Kotlin code following the language syntax. @@ -216,42 +216,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```kt -fun main() { - println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard kotlin conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/kotlin/stage-2/level-5/lesson.md b/lessons/kotlin/stage-2/level-5/lesson.md index 62d47ba..f8563a9 100644 --- a/lessons/kotlin/stage-2/level-5/lesson.md +++ b/lessons/kotlin/stage-2/level-5/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Kotlin:** -```kotlin +``` ALGORITHM: Decision Algorithms BEGIN @@ -39,7 +39,7 @@ BEGIN // Translate step by step into Kotlin // Test with sample inputs END -```kotlin +``` **Implementation Steps:** 1. Analyze what the algorithm does @@ -54,19 +54,19 @@ END ### How to Run 1. **Compile the code**: - ```bash + ``` kotlinc hello.kt - ```kotlin + ``` 2. **Run your program**: - ```bash + ``` kotlin hello - ```kotlin + ``` **Expected output:** -```kotlin +``` Hello, World! -```kotlin +``` ### How to Approach This @@ -165,7 +165,7 @@ The key is understanding what each pseudocode statement represents in Kotlin: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```kotlin +``` PSEUDOCODE: READ number IF number > 0 THEN @@ -173,7 +173,7 @@ PSEUDOCODE: ELSE PRINT "Not positive" END IF -```kotlin +``` This becomes structured Kotlin code following the language syntax. @@ -216,42 +216,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```kt -fun main() { - println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard kotlin conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/kotlin/stage-2/level-6/lesson.md b/lessons/kotlin/stage-2/level-6/lesson.md index c459465..3155f7a 100644 --- a/lessons/kotlin/stage-2/level-6/lesson.md +++ b/lessons/kotlin/stage-2/level-6/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Kotlin:** -```kotlin +``` ALGORITHM: Loop Algorithms BEGIN @@ -39,7 +39,7 @@ BEGIN // Translate step by step into Kotlin // Test with sample inputs END -```kotlin +``` **Implementation Steps:** 1. Analyze what the algorithm does @@ -54,19 +54,19 @@ END ### How to Run 1. **Compile the code**: - ```bash + ``` kotlinc hello.kt - ```kotlin + ``` 2. **Run your program**: - ```bash + ``` kotlin hello - ```kotlin + ``` **Expected output:** -```kotlin +``` Hello, World! -```kotlin +``` ### How to Approach This @@ -165,7 +165,7 @@ The key is understanding what each pseudocode statement represents in Kotlin: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```kotlin +``` PSEUDOCODE: READ number IF number > 0 THEN @@ -173,7 +173,7 @@ PSEUDOCODE: ELSE PRINT "Not positive" END IF -```kotlin +``` This becomes structured Kotlin code following the language syntax. @@ -216,42 +216,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```kt -fun main() { - println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard kotlin conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/kotlin/stage-2/level-7/lesson.md b/lessons/kotlin/stage-2/level-7/lesson.md index 962d330..02ccd46 100644 --- a/lessons/kotlin/stage-2/level-7/lesson.md +++ b/lessons/kotlin/stage-2/level-7/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Kotlin:** -```kotlin +``` ALGORITHM: Function Design BEGIN @@ -39,7 +39,7 @@ BEGIN // Translate step by step into Kotlin // Test with sample inputs END -```bash +``` **Implementation Steps:** 1. Analyze what the algorithm does @@ -54,19 +54,19 @@ END ### How to Run 1. **Compile the code**: - ```bash + ``` kotlinc hello.kt - ```kotlin + ``` 2. **Run your program**: - ```bash + ``` kotlin hello - ```kotlin + ``` **Expected output:** -```kotlin +``` Hello, World! -```kotlin +``` ### How to Approach This @@ -165,7 +165,7 @@ The key is understanding what each pseudocode statement represents in Kotlin: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```kotlin +``` PSEUDOCODE: READ number IF number > 0 THEN @@ -173,7 +173,7 @@ PSEUDOCODE: ELSE PRINT "Not positive" END IF -```kotlin +``` This becomes structured Kotlin code following the language syntax. @@ -216,42 +216,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```kt -fun main() { - println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard kotlin conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/kotlin/stage-3/level-1/lesson.md b/lessons/kotlin/stage-3/level-1/lesson.md index 135d805..af0464c 100644 --- a/lessons/kotlin/stage-3/level-1/lesson.md +++ b/lessons/kotlin/stage-3/level-1/lesson.md @@ -22,13 +22,13 @@ You're now ready for Stage 3! This is where you start thinking like a real progr Step 1: Write the pseudocode first -```kotlin +``` What should happen: 1. Print "Hello, [name]" Write your pseudocode in plain English below: (Your pseudocode here) -```bash +``` Step 2: Implement your pseudocode in Kotlin @@ -38,19 +38,19 @@ Create `main.kotlin.kotlin` with your solution. ### How to Run 1. **Compile the code**: - ```bash + ``` kotlinc hello.kt - ```kotlin + ``` 2. **Run your program**: - ```bash + ``` kotlin hello - ```kotlin + ``` **Expected output:** -```kotlin +``` Hello, World! -```kotlin +``` ### Success Checklist @@ -92,77 +92,26 @@ Check the `VIM_CHEATSHEET.md` for basic Vim commands! ## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown - -> **NEEDS_AUTHOR:** This lesson needs a complete answer key with code breakdown, execution process explanation, common errors table, and bonus knowledge section. Reference c-c++/stage-1/level-1/lesson.md for the gold standard format. - -### Key Concepts - -- Review the code structure specific to Kotlin -- Understand the execution flow -- Learn common pitfalls and solutions - -### Next Steps - -Practice the code and experiment with variations! - ---- - -**Congratulations! Keep coding!** - - - -### Additional Content - -Understand the key concepts: - -- Review each function -- Understand the flow -- Learn the patterns used - - -### Code Review - -Key functions and their purpose: - -- Main function: Entry point -- Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```kt -fun main() { - println("Hello, World!") -} +### Solution ``` +What should happen: +1. Print "Hello, [name]" -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: +Write your pseudocode in plain English below: +(Your pseudocode here) +``` -1. **Structure**: The program follows standard kotlin conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions +### Explanation -### Testing Your Solution +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -Try these test cases to verify your code works correctly: +### Success Criteria -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does -### Tips for Understanding +--- -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs +**Great job! You've completed this lesson!** diff --git a/lessons/kotlin/stage-3/level-2/lesson.md b/lessons/kotlin/stage-3/level-2/lesson.md index ba6f130..34f6e02 100644 --- a/lessons/kotlin/stage-3/level-2/lesson.md +++ b/lessons/kotlin/stage-3/level-2/lesson.md @@ -51,19 +51,19 @@ Data Structure Planning - Design an algorithm to solve this problem, then implem ### How to Run 1. **Compile the code**: - ```bash + ``` kotlinc hello.kt - ```kotlin + ``` 2. **Run your program**: - ```bash + ``` kotlin hello - ```kotlin + ``` **Expected output:** -```kotlin +``` Hello, World! -```kotlin +``` ### How to Approach This @@ -160,7 +160,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```kotlin +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -174,7 +174,7 @@ BEGIN - Step 3 4. Display results END -```kotlin +``` Then translate this directly to Kotlin code. @@ -217,42 +217,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```kt -fun main() { - println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard kotlin conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/kotlin/stage-3/level-3/lesson.md b/lessons/kotlin/stage-3/level-3/lesson.md index afc76ed..90cecdc 100644 --- a/lessons/kotlin/stage-3/level-3/lesson.md +++ b/lessons/kotlin/stage-3/level-3/lesson.md @@ -51,19 +51,19 @@ Mathematical Problems - Design an algorithm to solve this problem, then implemen ### How to Run 1. **Compile the code**: - ```bash + ``` kotlinc hello.kt - ```kotlin + ``` 2. **Run your program**: - ```bash + ``` kotlin hello - ```kotlin + ``` **Expected output:** -```kotlin +``` Hello, World! -```kotlin +``` ### How to Approach This @@ -160,7 +160,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```kotlin +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -174,7 +174,7 @@ BEGIN - Step 3 4. Display results END -```kotlin +``` Then translate this directly to Kotlin code. @@ -217,42 +217,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```kt -fun main() { - println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard kotlin conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/kotlin/stage-3/level-4/lesson.md b/lessons/kotlin/stage-3/level-4/lesson.md index 5458279..cf80c61 100644 --- a/lessons/kotlin/stage-3/level-4/lesson.md +++ b/lessons/kotlin/stage-3/level-4/lesson.md @@ -51,19 +51,19 @@ Text Processing Problems - Design an algorithm to solve this problem, then imple ### How to Run 1. **Compile the code**: - ```bash + ``` kotlinc hello.kt - ```kotlin + ``` 2. **Run your program**: - ```bash + ``` kotlin hello - ```kotlin + ``` **Expected output:** -```kotlin +``` Hello, World! -```kotlin +``` ### How to Approach This @@ -160,7 +160,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```kotlin +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -174,7 +174,7 @@ BEGIN - Step 3 4. Display results END -```kotlin +``` Then translate this directly to Kotlin code. @@ -217,42 +217,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```kt -fun main() { - println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard kotlin conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/kotlin/stage-3/level-5/lesson.md b/lessons/kotlin/stage-3/level-5/lesson.md index f910d4f..fcfc911 100644 --- a/lessons/kotlin/stage-3/level-5/lesson.md +++ b/lessons/kotlin/stage-3/level-5/lesson.md @@ -51,19 +51,19 @@ Logic Problems - Design an algorithm to solve this problem, then implement it. ### How to Run 1. **Compile the code**: - ```bash + ``` kotlinc hello.kt - ```kotlin + ``` 2. **Run your program**: - ```bash + ``` kotlin hello - ```kotlin + ``` **Expected output:** -```kotlin +``` Hello, World! -```kotlin +``` ### How to Approach This @@ -160,7 +160,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```kotlin +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -174,7 +174,7 @@ BEGIN - Step 3 4. Display results END -```kotlin +``` Then translate this directly to Kotlin code. @@ -217,42 +217,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```kt -fun main() { - println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard kotlin conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/kotlin/stage-3/level-6/lesson.md b/lessons/kotlin/stage-3/level-6/lesson.md index 4593764..c777034 100644 --- a/lessons/kotlin/stage-3/level-6/lesson.md +++ b/lessons/kotlin/stage-3/level-6/lesson.md @@ -51,19 +51,19 @@ Search Algorithms - Design an algorithm to solve this problem, then implement it ### How to Run 1. **Compile the code**: - ```bash + ``` kotlinc hello.kt - ```kotlin + ``` 2. **Run your program**: - ```bash + ``` kotlin hello - ```kotlin + ``` **Expected output:** -```kotlin +``` Hello, World! -```kotlin +``` ### How to Approach This @@ -160,7 +160,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```kotlin +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -174,7 +174,7 @@ BEGIN - Step 3 4. Display results END -```kotlin +``` Then translate this directly to Kotlin code. @@ -217,42 +217,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```kt -fun main() { - println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard kotlin conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/kotlin/stage-3/level-7/lesson.md b/lessons/kotlin/stage-3/level-7/lesson.md index 2684d7a..0cadde4 100644 --- a/lessons/kotlin/stage-3/level-7/lesson.md +++ b/lessons/kotlin/stage-3/level-7/lesson.md @@ -51,19 +51,19 @@ Sorting Algorithms - Design an algorithm to solve this problem, then implement i ### How to Run 1. **Compile the code**: - ```bash + ``` kotlinc hello.kt - ```kotlin + ``` 2. **Run your program**: - ```bash + ``` kotlin hello - ```kotlin + ``` **Expected output:** -```kotlin +``` Hello, World! -```kotlin +``` ### How to Approach This @@ -160,7 +160,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```kotlin +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -174,7 +174,7 @@ BEGIN - Step 3 4. Display results END -```kotlin +``` Then translate this directly to Kotlin code. @@ -217,42 +217,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```kt -fun main() { - println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard kotlin conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/kotlin/stage-4/level-1/lesson.md b/lessons/kotlin/stage-4/level-1/lesson.md index ce82719..dde2866 100644 --- a/lessons/kotlin/stage-4/level-1/lesson.md +++ b/lessons/kotlin/stage-4/level-1/lesson.md @@ -30,19 +30,19 @@ Requirements: ### How to Run 1. **Compile the code**: - ```bash + ``` kotlinc hello.kt - ```kotlin + ``` 2. **Run your program**: - ```bash + ``` kotlin hello - ```kotlin + ``` **Expected output:** -```kotlin +``` Hello, World! -```kotlin +``` ### How to Approach This @@ -120,42 +120,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```kt -fun main() { - println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard kotlin conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/kotlin/stage-4/level-2/lesson.md b/lessons/kotlin/stage-4/level-2/lesson.md index 345ead7..3ff9995 100644 --- a/lessons/kotlin/stage-4/level-2/lesson.md +++ b/lessons/kotlin/stage-4/level-2/lesson.md @@ -51,19 +51,19 @@ Build a complete Text Analysis Tool application that: ### How to Run 1. **Compile the code**: - ```bash + ``` kotlinc hello.kt - ```kotlin + ``` 2. **Run your program**: - ```bash + ``` kotlin hello - ```kotlin + ``` **Expected output:** -```kotlin +``` Hello, World! -```kotlin +``` ### How to Approach This @@ -163,13 +163,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```kotlin +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```kotlin +``` Build incrementally - get one feature working before adding the next. @@ -212,42 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```kt -fun main() { - println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard kotlin conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/kotlin/stage-4/level-3/lesson.md b/lessons/kotlin/stage-4/level-3/lesson.md index 02ff7f2..34847aa 100644 --- a/lessons/kotlin/stage-4/level-3/lesson.md +++ b/lessons/kotlin/stage-4/level-3/lesson.md @@ -51,19 +51,19 @@ Build a complete Data Processing application that: ### How to Run 1. **Compile the code**: - ```bash + ``` kotlinc hello.kt - ```kotlin + ``` 2. **Run your program**: - ```bash + ``` kotlin hello - ```kotlin + ``` **Expected output:** -```kotlin +``` Hello, World! -```kotlin +``` ### How to Approach This @@ -163,13 +163,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```kotlin +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```kotlin +``` Build incrementally - get one feature working before adding the next. @@ -212,42 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```kt -fun main() { - println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard kotlin conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/kotlin/stage-4/level-4/lesson.md b/lessons/kotlin/stage-4/level-4/lesson.md index 28ee16d..dbf5cf3 100644 --- a/lessons/kotlin/stage-4/level-4/lesson.md +++ b/lessons/kotlin/stage-4/level-4/lesson.md @@ -51,19 +51,19 @@ Build a complete File Operations application that: ### How to Run 1. **Compile the code**: - ```bash + ``` kotlinc hello.kt - ```kotlin + ``` 2. **Run your program**: - ```bash + ``` kotlin hello - ```kotlin + ``` **Expected output:** -```kotlin +``` Hello, World! -```kotlin +``` ### How to Approach This @@ -163,13 +163,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```kotlin +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```kotlin +``` Build incrementally - get one feature working before adding the next. @@ -212,42 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```kt -fun main() { - println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard kotlin conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/kotlin/stage-4/level-5/lesson.md b/lessons/kotlin/stage-4/level-5/lesson.md index 43fc1f3..440eaa9 100644 --- a/lessons/kotlin/stage-4/level-5/lesson.md +++ b/lessons/kotlin/stage-4/level-5/lesson.md @@ -51,19 +51,19 @@ Build a complete API Integration application that: ### How to Run 1. **Compile the code**: - ```bash + ``` kotlinc hello.kt - ```kotlin + ``` 2. **Run your program**: - ```bash + ``` kotlin hello - ```kotlin + ``` **Expected output:** -```kotlin +``` Hello, World! -```kotlin +``` ### How to Approach This @@ -163,13 +163,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```kotlin +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```kotlin +``` Build incrementally - get one feature working before adding the next. @@ -212,42 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```kt -fun main() { - println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard kotlin conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/kotlin/stage-4/level-6/lesson.md b/lessons/kotlin/stage-4/level-6/lesson.md index 95532fb..95b4622 100644 --- a/lessons/kotlin/stage-4/level-6/lesson.md +++ b/lessons/kotlin/stage-4/level-6/lesson.md @@ -51,19 +51,19 @@ Build a complete Database Operations application that: ### How to Run 1. **Compile the code**: - ```bash + ``` kotlinc hello.kt - ```kotlin + ``` 2. **Run your program**: - ```bash + ``` kotlin hello - ```kotlin + ``` **Expected output:** -```kotlin +``` Hello, World! -```kotlin +``` ### How to Approach This @@ -163,13 +163,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```kotlin +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```kotlin +``` Build incrementally - get one feature working before adding the next. @@ -212,42 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```kt -fun main() { - println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard kotlin conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/kotlin/stage-4/level-7/lesson.md b/lessons/kotlin/stage-4/level-7/lesson.md index 179ebd4..a5a8163 100644 --- a/lessons/kotlin/stage-4/level-7/lesson.md +++ b/lessons/kotlin/stage-4/level-7/lesson.md @@ -51,19 +51,19 @@ Build a complete Complete Application application that: ### How to Run 1. **Compile the code**: - ```bash + ``` kotlinc hello.kt - ```kotlin + ``` 2. **Run your program**: - ```bash + ``` kotlin hello - ```kotlin + ``` **Expected output:** -```kotlin +``` Hello, World! -```kotlin +``` ### How to Approach This @@ -163,13 +163,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```kotlin +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```kotlin +``` Build incrementally - get one feature working before adding the next. @@ -212,42 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```kt -fun main() { - println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard kotlin conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/kotlin/stage-5/level-1/lesson.md b/lessons/kotlin/stage-5/level-1/lesson.md index a376f01..1327e02 100644 --- a/lessons/kotlin/stage-5/level-1/lesson.md +++ b/lessons/kotlin/stage-5/level-1/lesson.md @@ -30,19 +30,19 @@ You're going to build a complete Kotlin application. This is a real project that ### How to Run 1. **Compile the code**: - ```bash + ``` kotlinc hello.kt - ```kotlin + ``` 2. **Run your program**: - ```bash + ``` kotlin hello - ```kotlin + ``` **Expected output:** -```kotlin +``` Hello, World! -```kotlin +``` ### Project Requirements @@ -161,42 +161,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```kt -fun main() { - println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard kotlin conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/kotlin/stage-5/level-2/lesson.md b/lessons/kotlin/stage-5/level-2/lesson.md index b857a94..8cd1f0a 100644 --- a/lessons/kotlin/stage-5/level-2/lesson.md +++ b/lessons/kotlin/stage-5/level-2/lesson.md @@ -58,19 +58,19 @@ Create a production-ready CLI Tool using Kotlin with: ### How to Run 1. **Compile the code**: - ```bash + ``` kotlinc hello.kt - ```kotlin + ``` 2. **Run your program**: - ```bash + ``` kotlin hello - ```kotlin + ``` **Expected output:** -```kotlin +``` Hello, World! -```kotlin +``` ### How to Approach This @@ -227,42 +227,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```kt -fun main() { - println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard kotlin conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/kotlin/stage-5/level-3/lesson.md b/lessons/kotlin/stage-5/level-3/lesson.md index 454ca52..6b073a8 100644 --- a/lessons/kotlin/stage-5/level-3/lesson.md +++ b/lessons/kotlin/stage-5/level-3/lesson.md @@ -58,19 +58,19 @@ Create a production-ready REST API using Kotlin with: ### How to Run 1. **Compile the code**: - ```bash + ``` kotlinc hello.kt - ```kotlin + ``` 2. **Run your program**: - ```bash + ``` kotlin hello - ```kotlin + ``` **Expected output:** -```kotlin +``` Hello, World! -```kotlin +``` ### How to Approach This @@ -227,42 +227,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```kt -fun main() { - println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard kotlin conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/kotlin/stage-5/level-4/lesson.md b/lessons/kotlin/stage-5/level-4/lesson.md index 296fbaa..471b7f4 100644 --- a/lessons/kotlin/stage-5/level-4/lesson.md +++ b/lessons/kotlin/stage-5/level-4/lesson.md @@ -58,19 +58,19 @@ Create a production-ready Data Visualization using Kotlin with: ### How to Run 1. **Compile the code**: - ```bash + ``` kotlinc hello.kt - ```kotlin + ``` 2. **Run your program**: - ```bash + ``` kotlin hello - ```kotlin + ``` **Expected output:** -```kotlin +``` Hello, World! -```kotlin +``` ### How to Approach This @@ -227,42 +227,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```kt -fun main() { - println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard kotlin conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/kotlin/stage-5/level-5/lesson.md b/lessons/kotlin/stage-5/level-5/lesson.md index ad94e45..090da67 100644 --- a/lessons/kotlin/stage-5/level-5/lesson.md +++ b/lessons/kotlin/stage-5/level-5/lesson.md @@ -58,19 +58,19 @@ Create a production-ready Automated Testing using Kotlin with: ### How to Run 1. **Compile the code**: - ```bash + ``` kotlinc hello.kt - ```kotlin + ``` 2. **Run your program**: - ```bash + ``` kotlin hello - ```kotlin + ``` **Expected output:** -```kotlin +``` Hello, World! -```kotlin +``` ### How to Approach This @@ -227,42 +227,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```kt -fun main() { - println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard kotlin conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/kotlin/stage-5/level-6/lesson.md b/lessons/kotlin/stage-5/level-6/lesson.md index 5cc2c4f..a2c30de 100644 --- a/lessons/kotlin/stage-5/level-6/lesson.md +++ b/lessons/kotlin/stage-5/level-6/lesson.md @@ -58,19 +58,19 @@ Create a production-ready Performance Optimization using Kotlin with: ### How to Run 1. **Compile the code**: - ```bash + ``` kotlinc hello.kt - ```kotlin + ``` 2. **Run your program**: - ```bash + ``` kotlin hello - ```kotlin + ``` **Expected output:** -```kotlin +``` Hello, World! -```kotlin +``` ### How to Approach This @@ -227,42 +227,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```kt -fun main() { - println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard kotlin conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/kotlin/stage-5/level-7/lesson.md b/lessons/kotlin/stage-5/level-7/lesson.md index e3577dd..a21f878 100644 --- a/lessons/kotlin/stage-5/level-7/lesson.md +++ b/lessons/kotlin/stage-5/level-7/lesson.md @@ -58,19 +58,19 @@ Create a production-ready Final Capstone Project using Kotlin with: ### How to Run 1. **Compile the code**: - ```bash + ``` kotlinc hello.kt - ```kotlin + ``` 2. **Run your program**: - ```bash + ``` kotlin hello - ```kotlin + ``` **Expected output:** -```kotlin +``` Hello, World! -```kotlin +``` ### How to Approach This @@ -227,42 +227,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```kt -fun main() { - println("Hello, World!") -} - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard kotlin conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/lua/stage-1/level-1/lesson.md b/lessons/lua/stage-1/level-1/lesson.md index 759b9e3..1b30716 100644 --- a/lessons/lua/stage-1/level-1/lesson.md +++ b/lessons/lua/stage-1/level-1/lesson.md @@ -25,9 +25,9 @@ Welcome to your first step into Lua programming! Today, you'll learn how to crea **Copy the following code EXACTLY as shown below into a new file called `hello.lua`** -```lua +``` print("Hello, World!") -```lua +``` --- @@ -35,18 +35,18 @@ print("Hello, World!") 1. **Open your terminal** (or command prompt) 2. **Navigate to where you saved your file**: - ```bash + ``` cd /path/to/your/folder - ```lua + ``` 3. **Run your program**: - ```bash + ``` lua hello.lua - ```bash + ``` **Expected output:** -```lua +``` Hello, World! -```lua +``` --- @@ -97,9 +97,9 @@ Remember to check the `VIM_CHEATSHEET.md` in the root directory for basic Vim co ### Code Breakdown -```lua +``` print("Hello, World!") -```lua +``` - **`print`** = Built-in function that outputs text to the console - **`()`** = Function call operator - executes the function with arguments - **`"Hello, World!"`** = String argument passed to the print function @@ -138,7 +138,7 @@ Lua can be run in several ways: --- - **Congratulations! You've written your first Lua program!** + **Congratulations! You've written your first Lua program!** *Keep moving forward - next up: Variables!* @@ -165,40 +165,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```lua -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard lua conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/lua/stage-1/level-2/lesson.md b/lessons/lua/stage-1/level-2/lesson.md index 215cad1..bd4761b 100644 --- a/lessons/lua/stage-1/level-2/lesson.md +++ b/lessons/lua/stage-1/level-2/lesson.md @@ -25,7 +25,7 @@ Welcome to the world of variables! Today you'll learn how to store and use data **Copy the following code into a new file called `variables.lua`** -```lua +``` -- String variables (text) name = "Alex" city = "New York" @@ -85,19 +85,19 @@ print("=== Table Example ===") print("Person name: " .. person.name) print("Person age: " .. person.age) print("First hobby: " .. person.hobbies[1]) -```lua +``` --- ### How to Execute 1. **Run your program**: - ```bash + ``` lua variables.lua - ```lua + ``` **Expected output:** -```lua +``` === Personal Info === Name: Alex City: New York @@ -123,7 +123,7 @@ Empty variable: nil Person name: Sam Person age: 30 First hobby: reading -```lua +``` --- @@ -178,32 +178,32 @@ Lua has several important concepts about variables: ### Code Breakdown -```lua +``` -- String variables (text) name = "Alex" -```lua +``` - **`--`** = Single-line comment (ignored by computer) - **`name`** = Variable name (no declaration keyword needed in Lua) - **`=`** = Assignment operator (stores value on right into variable on left) - **`"Alex"`** = String value (text in quotes) - No semicolon needed at the end of statements -```lua +``` age = 25 -```lua +``` - **`age`** = Variable name (numeric variable) - **`25`** = Number value (no quotes needed for numbers) - Lua treats integers and decimals as the same "number" type -```lua +``` is_student = true -```lua +``` - **`is_student`** = Boolean variable name (descriptive naming) - **`true`** = Boolean value (one of only two possible values: true or false) -```lua +``` print("Name: " .. name) -```lua +``` - **`..`** = String concatenation operator (joins strings together) - The variable `name` gets its value inserted into the output string @@ -211,7 +211,7 @@ print("Name: " .. name) In Lua, variables are global by default unless declared local: -```lua +``` -- Global variables (accessible anywhere) name = "Global" age = 25 @@ -219,7 +219,7 @@ age = 25 -- Local variables (only accessible in current scope) local local_name = "Local" local local_age = 30 -```lua +``` ### Variable Naming Rules @@ -249,7 +249,7 @@ local local_age = 30 Lua is dynamically typed, meaning: -```lua +``` dynamic = "I start as a string" print(type(dynamic)) -- Output: "string" @@ -258,13 +258,13 @@ print(type(dynamic)) -- Output: "number" dynamic = true -- Now it's a boolean print(type(dynamic)) -- Output: "boolean" -```lua +``` ### String Concatenation In Lua, use `..` for string concatenation: -```lua +``` first_name = "John" last_name = "Doe" @@ -275,13 +275,13 @@ print("Full name: " .. full_name) -- Note: You can't directly concatenate numbers and strings without conversion -- This will cause an error: print("Age: " .. 25) -- Instead, convert the number to string: print("Age: " .. tostring(25)) -```lua +``` ### Tables - Lua's Powerhouse Tables are Lua's most important data structure: -```lua +``` -- Array-like table (numeric indices) fruits = {"apple", "banana", "orange"} print(fruits[1]) -- Output: "apple" (1-indexed!) @@ -293,7 +293,7 @@ print(person.name) -- Output: "Alex" -- Mixed table mixed = {name = "Bob", years = {2020, 2021, 2022}} print(mixed.years[2]) -- Output: 2021 -```lua +``` ### Common Errors & Solutions @@ -315,7 +315,7 @@ print(mixed.years[2]) -- Output: 2021 Try this modified version: -```lua +``` -- Let's explore Lua's dynamic nature! print("=== Lua Advanced Variables ===") @@ -339,11 +339,11 @@ person = {name = "Alice", age = 28} person.job = "Engineer" -- Add new field person.age = person.age + 1 -- Update field print(person.name .. " is " .. person.age .. " years old and works as " .. person.job) -```lua +``` --- - **Excellent work! You now understand variables - the foundation of all programming!** + **Excellent work! You now understand variables - the foundation of all programming!** *Ready for the next challenge? Let's do some math with our variables!* @@ -370,40 +370,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```lua -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard lua conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/lua/stage-1/level-3/lesson.md b/lessons/lua/stage-1/level-3/lesson.md index d7785b2..268f65c 100644 --- a/lessons/lua/stage-1/level-3/lesson.md +++ b/lessons/lua/stage-1/level-3/lesson.md @@ -25,7 +25,7 @@ Time to do some math! Today you'll learn how to perform mathematical operations **Copy the following code into a new file called `math.lua`** -```lua +``` -- Basic arithmetic operations print("=== Basic Arithmetic ===") @@ -162,19 +162,19 @@ end if not nil and not false then print("Only nil and false are considered false") end -```lua +``` --- ### How to Execute 1. **Run your program**: - ```bash + ``` lua math.lua - ```lua + ``` **Expected output:** -```lua +``` === Basic Arithmetic === 5 + 3 = 8 10 - 4 = 6 @@ -223,7 +223,7 @@ Negative number: -25 === Boolean Logic with Numbers === In Lua, 0 is considered true in boolean context Only nil and false are considered false -```lua +``` *Note: Random numbers will vary each time you run the program* @@ -282,26 +282,26 @@ In Lua math, you saw some operators: ### Code Breakdown -```lua +``` sum = 5 + 3 print("5 + 3 = " .. sum) -```lua +``` - **`=`** = Assignment operator (stores the result of 5 + 3 into variable 'sum') - **`+`** = Addition operator (performs arithmetic addition) - **String concatenation**: The `..` operator joins strings and numbers (number automatically converted) -```lua +``` remainder = 17 % 5 print("17 % 5 = " .. remainder .. " (remainder)") -```lua +``` - **`%`** = Modulo operator (returns the remainder after division) - 17 ÷ 5 = 3 remainder 2, so 17 % 5 = 2 - Useful for checking if numbers are even (n % 2 == 0) or cycling through values -```lua +``` power = 2 ^ 3 print("2 ^ 3 = " .. power .. " (2 to the power of 3)") -```lua +``` - **`^`** = Exponentiation operator (raises left number to power of right number) - 2 ^ 3 = 2 to the power of 3 = 2 × 2 × 2 = 8 @@ -316,19 +316,19 @@ Lua follows the standard mathematical order of operations: 5. **M**odulo `%` (same precedence as multiplication and division) Examples: -```lua +``` -- Without parentheses: Multiplication before addition result = 10 + 5 * 2 -- = 10 + 10 = 20 (not 30!) -- With parentheses: Addition before multiplication result = (10 + 5) * 2 -- = 15 * 2 = 30 -```lua +``` ### Lua's Math Library Lua comes with a built-in math library for advanced operations: -```lua +``` -- Basic operations math.sqrt(16) -- Square root: 4 math.abs(-5) -- Absolute value: 5 @@ -347,11 +347,11 @@ math.cos(0) -- Cosine of 0: 1 -- Constants math.pi -- π: 3.141592653589793 math.huge -- Infinity -```lua +``` ### Random Number Generation -```lua +``` -- Seed the random generator (typically done once at program start) math.randomseed(os.time()) @@ -363,50 +363,50 @@ random_float = math.random() -- 0.0 to 1.0 -- Random integer between 1 and N random_single = math.random(10) -- Random 1-10 -```lua +``` ### Important Lua Math Notes **Number Type**: Lua has a single number type that handles both integers and floats: -```lua +``` integer_val = 42 -- Stored as number float_val = 3.14 -- Also stored as number print(type(integer_val)) -- Output: "number" print(type(float_val)) -- Output: "number" -```lua +``` **Division Results**: Division always returns a float: -```lua +``` print(6 / 3) -- Output: 2.0 (not 2) print(5 / 2) -- Output: 2.5 -```lua +``` **Division by Zero**: In Lua, dividing by zero results in inf (infinity): -```lua +``` print(5 / 0) -- Output: inf print(-5 / 0) -- Output: -inf -```lua +``` ### Comparison with Other Languages **No compound assignment operators**: Lua doesn't have `+=`, `-=`, `*=`, `/=` like other languages: -```lua +``` -- Instead of: value += 5 value = value + 5 -- Instead of: count++ count = count + 1 -```lua +``` **No integer division**: Lua doesn't have a special integer division operator like Python's `//`. Use math.floor for integer division: -```lua +``` result = math.floor(7 / 2) -- Result: 3 (integer division) -```lua +``` ### Common Errors & Solutions @@ -429,7 +429,7 @@ Lua math is used in various applications: Try this complex calculation: -```lua +``` print("=== Complex Math Example ===") -- Compound interest calculation @@ -455,11 +455,11 @@ side_a = 3 side_b = 4 hypotenuse = math.sqrt(side_a^2 + side_b^2) print("Right triangle with sides " .. side_a .. " and " .. side_b .. " has hypotenuse: " .. hypotenuse) -```lua +``` --- - **Excellent work! You're becoming a mathematical wizard in Lua!** + **Excellent work! You're becoming a mathematical wizard in Lua!** *Ready for the next challenge? Let's learn how to get input from users!* @@ -486,40 +486,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```lua -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard lua conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/lua/stage-1/level-4/lesson.md b/lessons/lua/stage-1/level-4/lesson.md index 57e0c63..340d422 100644 --- a/lessons/lua/stage-1/level-4/lesson.md +++ b/lessons/lua/stage-1/level-4/lesson.md @@ -25,7 +25,7 @@ Now let's make our programs interactive! Today you'll learn how to get input fro **Copy the following code into a new file called `input.lua`** -```lua +``` print("=== Interactive Greeting Program ===") -- Get input from user io.write("What's your name? ") -- io.write() doesn't add a newline @@ -120,19 +120,19 @@ if number ~= nil and number > 0 then else print("Invalid input! That wasn't a positive number.") end -```lua +``` --- ### How to Execute 1. **Run your program**: - ```bash + ``` lua input.lua - ```lua + ``` **Expected interaction:** -```lua +``` === Interactive Greeting Program === What's your name? [User types their name and presses Enter] Hello, [User's name]! Nice to meet you! @@ -147,7 +147,7 @@ What year were you born? [User enters a year] [Age calculation is performed and shown] [Additional prompts will ask for input and respond accordingly...] -```lua +``` --- @@ -200,23 +200,23 @@ What year were you born? [User enters a year] ### Code Breakdown -```lua +``` local name = io.read() -```lua +``` - **`io.read()`** = Function from the io library that reads from standard input - **Reads until** the user presses Enter - **Returns a string** containing whatever the user typed -```lua +``` local num1 = tonumber(io.read()) -```lua +``` - **`tonumber()`** = Converts string to number - **Necessary** because `io.read()` returns a string, but we want to do math - **Returns nil** if conversion fails (input wasn't a valid number) -```lua +``` io.write("What's your name? ") -```lua +``` - **`io.write()`** = Outputs text to the console - **Doesn't add** a newline character (unlike print) - **Useful for** prompts where user types on same line @@ -224,14 +224,14 @@ io.write("What's your name? ") ### Alternative Input Methods **Reading multiple values:** -```lua +``` -- Read multiple values on one line (space separated) local first, second = io.read("*number", "*number") print("First: " .. first .. ", Second: " .. second) -```lua +``` **Reading with different modes:** -```lua +``` -- Read one character local char = io.read(1) @@ -240,12 +240,12 @@ local content = io.read("*all") -- Read current line local line = io.read("*line") -```lua +``` ### Important Input Considerations **Always validate user input:** -```lua +``` local user_input = io.read() local number = tonumber(user_input) @@ -254,10 +254,10 @@ if number == nil then else print("You entered: " .. number) end -```lua +``` **Case sensitivity:** -```lua +``` -- Without string.lower(), "Paris" and "paris" would be different if answer == "Paris" then -- "paris" would not match -- This would fail if user types "paris" @@ -267,12 +267,12 @@ end if string.lower(answer) == "paris" then -- Works for any case -- This works regardless of case end -```lua +``` ### String Manipulation **Common string functions:** -```lua +``` -- Length of string local text = "Hello" print(string.len(text)) -- Output: 5 @@ -285,32 +285,32 @@ print(string.find(text, "ll")) -- Output: 3 (position where "ll" starts) -- Replace text (pattern matching) local new_text = string.gsub(text, "H", "h") -- "hello" -```lua +``` ### Error Prevention with Input **Safe number conversion:** -```lua +``` local get_number = function(prompt) io.write(prompt) local input = io.read() local num = tonumber(input) - + if num == nil then print("Invalid number! Please try again.") return get_number(prompt) -- Recursive call to try again end - + return num end -- Usage local age = get_number("Enter your age: ") -```lua +``` ### Date and Time in Lua -```lua +``` -- Get current date components local year = tonumber(os.date("%Y")) -- Full year (e.g., 2025) local month = tonumber(os.date("%m")) -- Month (01-12) @@ -318,7 +318,7 @@ local day = tonumber(os.date("%d")) -- Day (01-31) -- Get full date string local full_date = os.date("%Y-%m-%d") -- e.g., "2025-10-30" -```lua +``` ### Common Errors & Solutions @@ -332,17 +332,17 @@ local full_date = os.date("%Y-%m-%d") -- e.g., "2025-10-30" ### Best Practices for Input **Always validate user input:** -```lua +``` local age = tonumber(io.read()) if age == nil or age < 0 or age > 150 then print("Please enter a valid age between 0 and 150") else print("You are " .. age .. " years old") end -```lua +``` **Handle potential nil returns from tonumber:** -```lua +``` local input = io.read() local number = tonumber(input) if number ~= nil then @@ -351,7 +351,7 @@ if number ~= nil then else print("Invalid input - not a number") end -```lua +``` ### Security Considerations @@ -364,7 +364,7 @@ When accepting user input: Try this full interactive program: -```lua +``` print("=== Personal Finance Calculator ===") -- Get user's income @@ -402,11 +402,11 @@ if remaining > 0 then else print("You're spending more than you earn. Consider reducing expenses.") end -```lua +``` --- - **Excellent work! You now know how to make interactive programs that respond to user input!** + **Excellent work! You now know how to make interactive programs that respond to user input!** *Ready for the next challenge? Let's make programs that make decisions!* @@ -433,40 +433,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```lua -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard lua conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/lua/stage-1/level-5/lesson.md b/lessons/lua/stage-1/level-5/lesson.md index a654b70..0c21a78 100644 --- a/lessons/lua/stage-1/level-5/lesson.md +++ b/lessons/lua/stage-1/level-5/lesson.md @@ -25,7 +25,7 @@ Time to make programs that can make decisions! Today you'll learn how to write c **Copy the following code into a new file called `conditionals.lua`** -```lua +``` print("=== Simple Age Check ===") -- Input for age local age = 20 @@ -160,7 +160,7 @@ print("=== Alternative: Using Table as Switch ===") local days = { [1] = "Monday - start of the work week", [2] = "Tuesday", - [3] = "Wednesday - middle of the week", + [3] = "Wednesday - middle of the week", [4] = "Thursday", [5] = "Friday - weekend is almost here!", [6] = "Saturday - weekend fun!", @@ -188,19 +188,19 @@ local test_nil = nil local test_false = false if not test_nil then print("- nil is falsy") end if not test_false then print("- false is falsy") end -```lua +``` --- ### How to Execute 1. **Run your program**: - ```bash + ``` lua conditionals.lua - ```lua + ``` **Expected output:** -```lua +``` === Simple Age Check === You are an adult (18 or older) @@ -239,7 +239,7 @@ These values are truthy (evaluate to true in conditionals): Only these are falsy: - nil is falsy - false is falsy -```lua +``` --- @@ -299,20 +299,20 @@ In Lua conditionals, you'll use these comparison operators: ### Code Breakdown -```lua +``` if age >= 18 then print("You are an adult (18 or older)") else print("You are a minor (under 18)") end -```lua +``` - **`if`** = Start of conditional statement - **`age >= 18`** = Condition that evaluates to true or false - **`then`** = Keyword required after condition - **`end`** = Required to close the if block - **`else`** = Code block executed if condition is false -```lua +``` if grade >= 90 then print("Grade: A (90-100)") elseif grade >= 80 then @@ -322,18 +322,18 @@ elseif grade >= 70 then else print("Grade: F (below 60)") end -```lua +``` - **`elseif`** = Additional condition to check if the first was false - **Execution order** matters: Lua checks each condition in order and executes the first true one - **Only one block** executes, not multiple blocks -```lua +``` if username == "admin" and password == "secret123" then print("Login successful! Welcome, admin.") else print("Login failed! Invalid username or password.") end -```lua +``` - **`and`** = Logical AND operator (both conditions must be true) - **`==`** = Equality comparison operator - **Security** considerations: Never hardcode credentials in real programs @@ -341,13 +341,13 @@ end ### Comparison Operators Deep Dive **Equality vs Assignment:** -```lua +``` -- Wrong! This assigns a value (would cause an error in conditional) if username = "admin" then -- ERROR: Should be == -- Correct! This compares values if username == "admin" then -- OK: Comparison -```lua +``` ### Logical Operators @@ -358,7 +358,7 @@ if username == "admin" then -- OK: Comparison | NOT | `not` | Reverse condition | `not true` | `false` | **More Examples:** -```lua +``` -- AND: All conditions must be true local age = 21 local has_id = true @@ -380,11 +380,11 @@ local is_logged_in = false if not is_logged_in then print("Please log in first") end -```lua +``` ### Nested Conditionals -```lua +``` if number > 0 then print("The number is positive") if number % 2 == 0 then -- Nested if @@ -394,7 +394,7 @@ if number > 0 then end end end -```lua +``` - **Inner condition** only evaluated if outer condition is true - **Be careful** with nesting - too deep can be hard to read @@ -410,7 +410,7 @@ This is a major difference from other languages! - Any other number - Any table, function, thread, userdata -```lua +``` -- Examples if 0 then print("0 is truthy in Lua!") end -- This prints! if "" then print("Empty string is truthy in Lua!") end -- This prints! @@ -419,13 +419,13 @@ if -1 then print("-1 is truthy in Lua!") end -- This prints! -- Only nil and false are falsy if not nil then print("nil is falsy in Lua") end -- This prints! if not false then print("false is falsy in Lua") end -- This prints! -```lua +``` **This is different from JavaScript, Python, C++, etc. where 0 and empty strings are falsy!** ### Control Flow with Logical Operators -```lua +``` -- Short-circuit evaluation local result = true and print("This will print") -- print() returns nil, which is assigned to result @@ -433,11 +433,11 @@ local result = true and print("This will print") -- Useful patterns local name = user_input or "Anonymous" -- Use default if user_input is nil local value = some_condition and "yes" or "no" -- Ternary-like operation -```lua +``` ### Switch Alternative with Tables -```lua +``` -- Instead of long if-elseif chains, you can use a table: local actions = { fire = function() print("Fire attack!") end, @@ -450,7 +450,7 @@ local action = actions[element] if action then action() -- Execute the fire attack function end -```lua +``` ### Common Errors & Solutions @@ -465,7 +465,7 @@ end ### Best Practices for Conditionals **Use descriptive variable names:** -```lua +``` -- Good if is_adult then ... end if is_valid_email then ... end @@ -473,17 +473,17 @@ if is_valid_email then ... end -- Avoid if x then ... end if flag then ... end -```lua +``` **Keep conditions simple:** -```lua +``` -- Good - store complex condition in variable local can_vote = age >= 18 and is_citizen and not is_in_prison if can_vote then ... end -- Avoid - hard to read if age >= 18 and is_citizen and not is_in_prison then ... end -```lua +``` **Consider table lookup vs if/elseif:** - Use `if/elseif` for complex conditions and ranges @@ -493,7 +493,7 @@ if age >= 18 and is_citizen and not is_in_prison then ... end Try this complex conditional program: -```lua +``` print("=== Advanced Conditional Example ===") -- A simple grading system with lots of conditions @@ -561,11 +561,11 @@ elseif overall_score >= 60 then else print("Not eligible for graduation, must repeat course") end -```lua +``` --- - **Excellent work! You now understand how to make your programs make intelligent decisions!** + **Excellent work! You now understand how to make your programs make intelligent decisions!** *Ready for the next challenge? Let's learn about loops and repetition!* @@ -592,40 +592,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```lua -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard lua conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/lua/stage-1/level-6/lesson.md b/lessons/lua/stage-1/level-6/lesson.md index 2787b80..b451059 100644 --- a/lessons/lua/stage-1/level-6/lesson.md +++ b/lessons/lua/stage-1/level-6/lesson.md @@ -26,7 +26,7 @@ Time to make your programs repeat actions! Today you'll learn how to write code **Copy the following code into a new file called `loops.lua`** -```lua +``` print("=== Numeric For Loop - Counting ===") -- Basic numeric for loop: for variable = start, stop, step for i = 1, 5 do @@ -110,7 +110,7 @@ repeat tries = tries + 1 menu_choice = math.random(1, 4) -- Random 1-4 print("Menu attempt #" .. tries .. ": Option " .. menu_choice) - + if menu_choice == 3 then print("Option 3 selected! Exiting menu.") end @@ -182,19 +182,19 @@ for i, num in ipairs(numbers) do end print("Total sum: " .. total) -```lua +``` --- ### How to Execute 1. **Run your program**: - ```bash + ``` lua loops.lua - ```lua + ``` **Expected output:** -```lua +``` === Numeric For Loop - Counting === Count: 1 Count: 2 @@ -213,7 +213,7 @@ Countdown: 4 Countdown: 3 Countdown: 2 Countdown: 1 -Blast off! +Blast off! === Numeric For Loop - Even Numbers === Even number: 2 @@ -278,16 +278,16 @@ Odd number: 7 Odd number: 9 === Nested Loops - Multiplication Table === -1 2 3 -2 4 6 -3 6 9 +1 2 3 +2 4 6 +3 6 9 === Pattern - Stars === -* -* * -* * * -* * * * -* * * * * +* +* * +* * * +* * * * +* * * * * === Looping with Table Length === Color 1: red @@ -304,7 +304,7 @@ Processing number 3: 30 Processing number 4: 40 Processing number 5: 50 Total sum: 150 -```lua +``` *Note: Random numbers will vary each time you run the program* --- @@ -356,11 +356,11 @@ Total sum: 150 ### Code Breakdown -```lua +``` for i = 1, 5 do print("Count: " .. i) end -```lua +``` - **`for`** = Loop keyword - **`i = 1, 5`** = Loop variable starts at 1, ends at 5 (inclusive) - **`, 1`** = Step is optional, defaults to 1 @@ -368,28 +368,28 @@ end - **`end`** = Required keyword to end the loop block - **Loop execution**: 1, 2, 3, 4, 5 (stops after 5) -```lua +``` for i = 10, 1, -1 do print("Countdown: " .. i) end -```lua +``` - **`10, 1, -1`** = Start at 10, stop at 1, step by -1 (counting backwards) -```lua +``` while count <= 5 do print("While count: " .. count) count = count + 1 -- Critical: must update the counter! end -```lua +``` - **`while`** = Loop that continues while condition is true - **Condition checked first** before each iteration - **`count = count + 1`** = Must update counter inside the loop or it runs forever! -```lua +``` repeat print("Menu attempt #" .. tries .. ": Option " .. menu_choice) until menu_choice == 3 -```lua +``` - **`repeat`** = Code block executes first - **`until`** = Then condition is checked - **Result**: Block runs at least once regardless of condition @@ -397,7 +397,7 @@ until menu_choice == 3 ### For Loop Variations **Numeric for loop variations:** -```lua +``` -- Basic: for variable = start, stop, step for i = 1, 5 do -- i: 1, 2, 3, 4, 5 print(i) @@ -410,12 +410,12 @@ end for i = 10, 1, -1 do -- i: 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 print(i) end -```lua +``` ### Table Iteration Methods **ipairs() vs pairs():** -```lua +``` -- ipairs() - iterates in numerical order with integer indices local arr = {"a", "b", "c"} for i, v in ipairs(arr) do @@ -427,22 +427,22 @@ local t = {name = "Alex", age = 25, [1] = "first"} for k, v in pairs(t) do print(k, v) -- Could print in any order end -```lua +``` ### Loop Control **break** = Exits the loop completely: -```lua +``` for i = 1, 10 do if i == 5 then break -- Loop stops here end print(i) -- Prints: 1, 2, 3, 4 end -```lua +``` Lua doesn't have a continue keyword, but you can achieve similar effects with if-then-else: -```lua +``` for i = 1, 5 do if i ~= 3 then -- Skip when i equals 3 print(i) -- Prints: 1, 2, 4, 5 (skips 3) @@ -450,19 +450,19 @@ for i = 1, 5 do print("Skipped " .. i) end end -```lua +``` ### Nested Loops -```lua +``` for i = 1, 3 do -- Outer loop for j = 1, 3 do -- Inner loop print("i=" .. i .. ", j=" .. j) end end -```lua +``` **Output:** -```lua +``` i=1, j=1 i=1, j=2 i=1, j=3 @@ -472,18 +472,18 @@ i=2, j=3 i=3, j=1 i=3, j=2 i=3, j=3 -```lua +``` - **Inner loop** completes all iterations for each outer loop iteration - **Total iterations**: 3 × 3 = 9 ### Table Length with # -```lua +``` local arr = {"apple", "banana", "orange"} for i = 1, #arr do -- #arr returns 3 print(arr[i]) end -```lua +``` **Note**: The `#` operator only works predictably on sequences (arrays with consecutive integer keys starting from 1). ### Common Errors & Solutions @@ -522,14 +522,14 @@ end Try this complex loop program: -```lua +``` print("=== Advanced Loop Examples ===") -- Prime number finder print("Prime numbers from 2 to 30:") for num = 2, 30 do local is_prime = true - + -- Check if num is divisible by any number from 2 to sqrt(num) for divisor = 2, math.sqrt(num) do if num % divisor == 0 then @@ -537,7 +537,7 @@ for num = 2, 30 do break -- Found a divisor, not prime end end - + if is_prime then print(num .. " is prime") end @@ -577,11 +577,11 @@ for i = 1, 5 do end print(row) end -```lua +``` --- - **Excellent work! You now understand how to repeat actions efficiently with loops!** + **Excellent work! You now understand how to repeat actions efficiently with loops!** *Ready for the next challenge? Let's learn about functions - the building blocks of reusable code!* @@ -608,40 +608,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```lua -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard lua conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/lua/stage-1/level-7/lesson.md b/lessons/lua/stage-1/level-7/lesson.md index be016db..009d422 100644 --- a/lessons/lua/stage-1/level-7/lesson.md +++ b/lessons/lua/stage-1/level-7/lesson.md @@ -26,7 +26,7 @@ Welcome to the world of functions! Today you'll learn how to organize your code **Copy the following code into a new file called `functions.lua`** -```lua +``` print("=== Basic Function Definition ===") -- Define a function that greets someone function greet_user() @@ -159,7 +159,7 @@ function scope_demo() local local_variable = "I'm local!" print("Inside function: " .. global_variable) print("Inside function: " .. local_variable) - + -- Functions can modify global variables (though not recommended) global_variable = "Modified from inside function!" end @@ -179,7 +179,7 @@ function outer_function(name) local function inner_function() return "Hello from inside!" end - + return name .. ", " .. inner_function() end @@ -248,19 +248,19 @@ print("Counter 1: " .. counter1()) -- 2 print("Counter 2: " .. counter2()) -- 1 (independent counter) print("Counter 1: " .. counter1()) -- 3 print("Counter 2: " .. counter2()) -- 2 -```lua +``` --- ### How to Execute 1. **Run your program**: - ```bash + ``` lua functions.lua - ```lua + ``` **Expected output:** -```lua +``` === Basic Function Definition === Hello! Welcome to the wonderful world of functions! Hello! Welcome to the wonderful world of functions! @@ -318,7 +318,7 @@ Counter 1: 2 Counter 2: 1 Counter 1: 3 Counter 2: 2 -```lua +``` --- @@ -370,29 +370,29 @@ Counter 2: 2 ### Code Breakdown -```lua +``` function greet_user() print("Hello! Welcome to the wonderful world of functions!") end -```lua +``` - **`function`** = Keyword to declare a function - **`greet_user`** = Function name (follows variable naming rules) - **`()`** = Parameters (empty because no parameters needed) - **`end`** = Required to close the function definition - **No return** = Function runs code but doesn't return a value -```lua +``` function greet_by_name(name) print("Hello, " .. name .. "! Nice to meet you!") end -```lua +``` - **`name`** = Parameter (variable that receives the argument value) - **Parameters** = Variables defined in function declaration - **Arguments** = Actual values passed when calling the function -```lua +``` local result1 = add_numbers(5, 3) -```lua +``` - **`add_numbers(5, 3)`** = Function call with arguments - **`5` and `3`** = Arguments passed to the function - **Return value** = Value that function sends back @@ -401,46 +401,46 @@ local result1 = add_numbers(5, 3) ### Function Declaration vs Expression **Function Declaration (Traditional):** -```lua +``` function add(a, b) return a + b end -- Can be called before or after the declaration -```lua +``` **Function Expression:** -```lua +``` local add = function(a, b) return a + b end -- Must be defined before calling -```lua +``` ### Multiple Return Values One unique feature of Lua is that functions can return multiple values: -```lua +``` function get_coordinates() return 10, 20, 30 -- x, y, z coordinates end local x, y, z = get_coordinates() print(x, y, z) -- Output: 10 20 30 -```lua +``` ### Function Parameters **Default parameters** (Lua 5.4+): -```lua -function greet(name, greeting) +``` +function greet(name, greeting) greeting = greeting or "Hello" -- Use "Hello" if greeting is nil print(greeting .. ", " .. name .. "!") end -```lua +``` **Variadic parameters** (...): -```lua +``` function sum_all(...) local args = {...} -- Create table from all arguments local total = 0 @@ -449,27 +449,27 @@ function sum_all(...) end return total end -```lua +``` ### Function Scope **Global scope:** -```lua +``` local global_var = "I'm accessible in functions" -```lua +``` **Local scope:** -```lua +``` function my_function() local local_var = "I'm only accessible inside this function" -- Can access both global_var and local_var end -- Can access global_var but NOT local_var -```lua +``` **Important:** In Lua, variables are global by default unless declared `local`: -```lua +``` -- This creates a global variable function set_global() accidentally_global = "This is global!" @@ -479,40 +479,40 @@ end function set_local() local intentionally_local = "This is local!" end -```lua +``` ### Return Values **Functions without return:** -```lua +``` function say_hello() print("Hello!") end -- Returns 'nil' implicitly -```lua +``` **Functions with return:** -```lua +``` function get_hello() return "Hello!" end -- Returns "Hello!" which can be stored in a variable -```lua +``` **Multiple returns:** -```lua +``` function divide_with_remainder(a, b) return math.floor(a / b), a % b -- quotient, remainder end local quotient, remainder = divide_with_remainder(17, 5) -- 3, 2 -```lua +``` ### Closures A closure is a function that captures variables from its outer scope: -```lua +``` function create_multiplier(factor) return function(number) return number * factor -- 'factor' captured from outer scope @@ -524,13 +524,13 @@ local triple = create_multiplier(3) print(double(5)) -- Output: 10 print(triple(5)) -- Output: 15 -```lua +``` ### Higher-Order Functions Functions that take other functions as parameters or return functions: -```lua +``` -- Function that takes another function as a parameter function execute_twice(func) func() @@ -542,28 +542,28 @@ function say_hello() end execute_twice(say_hello) -- Will output "Hello!" twice -```lua +``` ### Pure vs Impure Functions **Pure function:** - Same input always gives same output - No side effects (doesn't modify external state) -```lua +``` function add(a, b) return a + b -- Pure function end -```lua +``` **Impure function:** - May have side effects or depend on external state -```lua +``` local count = 0 function increment() count = count + 1 -- Modifies external variable return count end -- Impure function -```lua +``` ### Common Errors & Solutions @@ -578,7 +578,7 @@ end -- Impure function ### Best Practices for Functions **Function naming:** -```lua +``` -- Good - descriptive names function calculate_area(length, width) ... end function is_valid_email(email) ... end @@ -587,10 +587,10 @@ function send_notification(message) ... end -- Avoid - vague names function do_stuff() ... end function process() ... end -```lua +``` **Use local variables:** -```lua +``` -- Good - limits scope of variables function calculate_total(items) local total = 0 @@ -600,7 +600,7 @@ function calculate_total(items) end return total end -```lua +``` **Function size:** - Keep functions focused on a single task @@ -608,7 +608,7 @@ end - If a function gets too long, consider breaking it into smaller ones **Single Responsibility Principle:** -```lua +``` -- Good - one purpose function calculate_tax(amount, rate) return amount * rate @@ -621,13 +621,13 @@ function process_order(order) -- ... other processing return total end -```lua +``` ### Advanced Challenge (For the Brave!) Try this comprehensive function example: -```lua +``` print("=== Banking Application with Functions ===") -- Function to create a bank account object @@ -646,7 +646,7 @@ function deposit(account, amount) print("Deposit amount must be positive!") return false end - + account.balance = account.balance + amount table.insert(account.transactions, { type = "deposit", @@ -654,7 +654,7 @@ function deposit(account, amount) date = os.date("%Y-%m-%d"), balance_after = account.balance }) - + print("$" .. amount .. " deposited. New balance: $" .. account.balance) return true end @@ -665,20 +665,20 @@ function withdraw(account, amount) print("Withdrawal amount must be positive!") return false end - + if amount > account.balance then print("Insufficient funds! Current balance: $" .. account.balance) return false end - + account.balance = account.balance - amount table.insert(account.transactions, { - type = "withdrawal", + type = "withdrawal", amount = amount, date = os.date("%Y-%m-%d"), balance_after = account.balance }) - + print("$" .. amount .. " withdrawn. New balance: $" .. account.balance) return true end @@ -693,7 +693,7 @@ end function get_transaction_history(account) print(account.name .. "'s Transaction History:") for i, transaction in ipairs(account.transactions) do - print(transaction.date .. " - " .. transaction.type .. ": $" .. + print(transaction.date .. " - " .. transaction.type .. ": $" .. transaction.amount .. " - Balance: $" .. transaction.balance_after) end end @@ -702,7 +702,7 @@ end function transfer(from_account, to_account, amount) if withdraw(from_account, amount) then deposit(to_account, amount) - print("Transfer of $" .. amount .. " from " .. from_account.name .. + print("Transfer of $" .. amount .. " from " .. from_account.name .. " to " .. to_account.name .. " completed!") return true end @@ -722,11 +722,11 @@ check_balance(taylor_account) print() get_transaction_history(alex_account) -```lua +``` --- - **Excellent work! You now understand how to organize code using functions - a fundamental skill for all programmers!** + **Excellent work! You now understand how to organize code using functions - a fundamental skill for all programmers!** *This completes Stage 1 of Lua learning! You've mastered the fundamentals of Lua programming. Great job!* @@ -753,40 +753,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```lua -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard lua conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/lua/stage-2/level-1/lesson.md b/lessons/lua/stage-2/level-1/lesson.md index e09bb5b..c7bc1a4 100644 --- a/lessons/lua/stage-2/level-1/lesson.md +++ b/lessons/lua/stage-2/level-1/lesson.md @@ -26,7 +26,7 @@ Welcome to Stage 2! You've mastered copying code - now it's time to think like a **Pseudocode** is a way to write programming logic in plain English (or your native language) before writing actual code. It's like writing a recipe or instructions for a task. **Example:** -```lua +``` Algorithm: Make a sandwich 1. Get bread from pantry 2. Get peanut butter from fridge @@ -35,7 +35,7 @@ Algorithm: Make a sandwich 5. Spread jelly on the other bread slice 6. Put slices together 7. Enjoy your sandwich! -```lua +``` This is much easier to understand than trying to write code first! @@ -51,25 +51,25 @@ This is much easier to understand than trying to write code first! ### How to Run 1. **Run the code**: - ```bash + ``` lua hello.lua - ```lua + ``` **Expected output:** -```lua +``` Hello, World! -```lua +``` ## Algorithm 1: Greeting Program **Pseudocode:** -```lua +``` Algorithm: Display Personal Greeting 1. Display "Hello! What's your name?" to the user 2. Get the user's name from input 3. Display "Nice to meet you, " followed by the user's name 4. Display "Welcome to programming!" -```lua +``` **Your Task:** Create a Lua program that follows these exact steps. @@ -78,7 +78,7 @@ Algorithm: Display Personal Greeting ## Algorithm 2: Simple Calculator **Pseudocode:** -```lua +``` Algorithm: Add Two Numbers 1. Ask user for first number 2. Get first number from user @@ -86,7 +86,7 @@ Algorithm: Add Two Numbers 4. Get second number from user 5. Calculate sum of the two numbers 6. Display "The sum is: " followed by the sum -```lua +``` **Your Task:** Create a Lua program that implements this calculator. @@ -95,14 +95,14 @@ Algorithm: Add Two Numbers ## Algorithm 3: Age Calculator **Pseudocode:** -```lua +``` Algorithm: Calculate Age in Days 1. Display "Enter your age in years: " 2. Get age in years from user 3. Calculate days = age × 365 4. Display "You are approximately " + days + " days old" 5. Display "That's a lot of days!" -```lua +``` **Your Task:** Create a program that calculates approximate age in days. @@ -111,7 +111,7 @@ Algorithm: Calculate Age in Days ## Algorithm 4: Temperature Converter **Pseudocode:** -```lua +``` Algorithm: Celsius to Fahrenheit Converter 1. Display "Enter temperature in Celsius: " 2. Get temperature in Celsius from user @@ -120,7 +120,7 @@ Algorithm: Celsius to Fahrenheit Converter 5. Display "°C = " 6. Display the Fahrenheit temperature 7. Display "°F" -```lua +``` **Your Task:** Create a temperature conversion program. @@ -129,7 +129,7 @@ Algorithm: Celsius to Fahrenheit Converter ## Algorithm 5: Rectangle Area Calculator **Pseudocode:** -```lua +``` Algorithm: Calculate Rectangle Area 1. Display "Rectangle Area Calculator" 2. Display "Enter length: " @@ -140,7 +140,7 @@ Algorithm: Calculate Rectangle Area 7. Calculate perimeter = 2 × (length + width) 8. Display "Area: " + area 9. Display "Perimeter: " + perimeter -```lua +``` **Your Task:** Create a program that calculates both area and perimeter. @@ -149,7 +149,7 @@ Algorithm: Calculate Rectangle Area ## Algorithm 6: Simple Interest Calculator **Pseudocode:** -```lua +``` Algorithm: Calculate Simple Interest 1. Display "Simple Interest Calculator" 2. Display "Enter principal amount: $" @@ -163,7 +163,7 @@ Algorithm: Calculate Simple Interest 10. Display "Principal: $" + principal 11. Display "Interest: $" + interest 12. Display "Total: $" + total -```lua +``` **Your Task:** Implement the complete interest calculation. @@ -172,7 +172,7 @@ Algorithm: Calculate Simple Interest ## Algorithm 7: BMI Calculator **Pseudocode:** -```lua +``` Algorithm: Calculate Body Mass Index 1. Display "BMI Calculator" 2. Display "Enter weight in kg: " @@ -189,7 +189,7 @@ Algorithm: Calculate Body Mass Index Display "Category: Overweight" 11. Else Display "Category: Obesity" -```lua +``` **Your Task:** Create a program that calculates BMI with categorization. @@ -245,7 +245,7 @@ Algorithm: Calculate Body Mass Index ## Pseudocode Best Practices ### Good Pseudocode -```lua +``` Algorithm: Process User Data 1. Get user's name 2. Get user's age @@ -254,18 +254,18 @@ Algorithm: Process User Data Else Display "Minor user" 4. Display "Data processed" -```lua +``` ### Bad Pseudocode (Too Vague) -```lua +``` Algorithm: Do stuff 1. Get things 2. Calculate something 3. Show results -```lua +``` ### Good Pseudocode (Clear and Specific) -```lua +``` Algorithm: Calculate BMI 1. Display "BMI Calculator" 2. Display "Enter weight in kg: " @@ -274,7 +274,7 @@ Algorithm: Calculate BMI 5. Get height from user 6. Calculate BMI = weight ÷ (height × height) 7. Display "Your BMI is: " + BMI -```lua +``` --- @@ -286,7 +286,7 @@ Algorithm: Calculate BMI ### Algorithm 1: Greeting Program -```lua +``` print("Algorithm 1: Greeting Program") -- Display "Hello! What's your name?" to the user @@ -298,11 +298,11 @@ print("Nice to meet you, " .. name) -- Display "Welcome to programming!" print("Welcome to programming!") -```lua +``` ### Algorithm 2: Simple Calculator -```lua +``` print("Algorithm 2: Simple Calculator") -- Ask user for first number @@ -318,11 +318,11 @@ local sum = first_num + second_num -- Display "The sum is: " followed by the sum print("The sum is: " .. sum) -```lua +``` ### Algorithm 3: Age Calculator -```lua +``` print("Algorithm 3: Age Calculator") -- Display "Enter your age in years: " @@ -335,11 +335,11 @@ local days = age * 365 -- Display messages print("You are approximately " .. days .. " days old") print("That's a lot of days!") -```lua +``` ### Algorithm 4: Temperature Converter -```lua +``` print("Algorithm 4: Temperature Converter") -- Display "Enter temperature in Celsius: " @@ -351,11 +351,11 @@ local fahrenheit = (celsius * 9/5) + 32 -- Display the results print(celsius .. "°C = " .. fahrenheit .. "°F") -```lua +``` ### Algorithm 5: Rectangle Area Calculator -```lua +``` print("Rectangle Area Calculator") -- Get length from user @@ -375,11 +375,11 @@ local perimeter = 2 * (length + width) -- Display results print("Area: " .. area) print("Perimeter: " .. perimeter) -```lua +``` ### Algorithm 6: Simple Interest Calculator -```lua +``` print("Simple Interest Calculator") -- Get principal from user @@ -404,11 +404,11 @@ local total = principal + interest print("Principal: $" .. string.format("%.2f", principal)) print("Interest: $" .. string.format("%.2f", interest)) print("Total: $" .. string.format("%.2f", total)) -```lua +``` ### Algorithm 7: BMI Calculator -```lua +``` print("BMI Calculator") -- Get weight from user @@ -435,7 +435,7 @@ elseif bmi < 30 then else print("Category: Obesity") end -```lua +``` ### Common Translation Patterns @@ -480,27 +480,27 @@ end ### Input/Output Patterns **Getting Numbers:** -```lua +``` io.write("Enter age: ") local age = tonumber(io.read()) -```lua +``` **Getting Text:** -```lua +``` io.write("Enter name: ") local name = io.read() -```lua +``` **Displaying Results:** -```lua +``` print("Result: " .. result) print("Price: $" .. string.format("%.2f", price)) print("Hello, " .. name .. "!") -```lua +``` --- - **Congratulations! You've translated your first pseudocode algorithms into working Lua programs!** + **Congratulations! You've translated your first pseudocode algorithms into working Lua programs!** *This is a major milestone - you're now thinking like a programmer! Next up: Variables in pseudocode!* @@ -520,40 +520,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```lua -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard lua conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/lua/stage-2/level-2/lesson.md b/lessons/lua/stage-2/level-2/lesson.md index 4b5f17f..bbeac68 100644 --- a/lessons/lua/stage-2/level-2/lesson.md +++ b/lessons/lua/stage-2/level-2/lesson.md @@ -26,25 +26,25 @@ Welcome to Level 2! Today we're focusing on how to handle variables in your pseu Variables in pseudocode follow simple patterns: **Declaration and assignment:** -```lua +``` SET name TO "John" SET age TO 25 SET is_student TO TRUE -```lua +``` **Reassignment:** -```lua +``` SET age TO age + 1 SET total TO total + new_value SET is_student TO FALSE -```lua +``` **Calculations with variables:** -```lua +``` SET area TO length * width SET average TO (num1 + num2 + num3) / 3 SET is_adult TO age >= 18 -```lua +``` --- @@ -58,19 +58,19 @@ SET is_adult TO age >= 18 ### How to Run 1. **Run the code**: - ```bash + ``` lua hello.lua - ```lua + ``` **Expected output:** -```lua +``` Hello, World! -```lua +``` ## Algorithm 1: Simple Variable Swapping **Pseudocode:** -```lua +``` Algorithm: Swap Two Variables 1. SET first_number TO 10 2. SET second_number TO 20 @@ -79,7 +79,7 @@ Algorithm: Swap Two Variables 5. SET first_number TO second_number 6. SET second_number TO temp 7. DISPLAY "After swap: first=" + first_number + ", second=" + second_number -```lua +``` **Your Task:** Create a Lua program that demonstrates variable swapping. @@ -88,7 +88,7 @@ Algorithm: Swap Two Variables ## Algorithm 2: Running Total Calculator **Pseudocode:** -```lua +``` Algorithm: Calculate Running Total 1. SET total TO 0 2. SET count TO 0 @@ -105,7 +105,7 @@ Algorithm: Calculate Running Total 13. DISPLAY "Total: " + total 14. DISPLAY "Count: " + count 15. DISPLAY "Average: " + average -```lua +``` **Your Task:** Create a Lua program that calculates a running total and average. @@ -114,7 +114,7 @@ Algorithm: Calculate Running Total ## Algorithm 3: Temperature Tracker **Pseudocode:** -```lua +``` Algorithm: Track Temperature Readings 1. SET min_temp TO 100 2. SET max_temp TO -100 @@ -136,7 +136,7 @@ Algorithm: Track Temperature Readings 13. IF current_temp > max_temp THEN SET max_temp TO current_temp 14. DISPLAY "Current: " + current_temp + ", Min: " + min_temp + ", Max: " + max_temp -```lua +``` **Your Task:** Create a Lua program that tracks min/max temperatures. @@ -145,7 +145,7 @@ Algorithm: Track Temperature Readings ## Algorithm 4: Account Balance Tracker **Pseudocode:** -```lua +``` Algorithm: Track Bank Account Balance 1. SET account_balance TO 1000 2. SET transaction_amount TO -50 @@ -160,7 +160,7 @@ Algorithm: Track Bank Account Balance 11. SET transaction_amount TO 150.25 12. SET account_balance TO account_balance + transaction_amount 13. DISPLAY "Balance after deposit: $" + account_balance -```lua +``` **Your Task:** Create a Lua program that tracks account balance changes. @@ -169,7 +169,7 @@ Algorithm: Track Bank Account Balance ## Algorithm 5: Student Grade Calculator **Pseudocode:** -```lua +``` Algorithm: Calculate Student Grade 1. SET total_points TO 0 2. SET possible_points TO 0 @@ -195,7 +195,7 @@ Algorithm: Calculate Student Grade 22. DISPLAY "Possible Points: " + possible_points 23. DISPLAY "Percentage: " + percentage 24. DISPLAY "Letter Grade: " + letter_grade -```lua +``` **Your Task:** Create a Lua program that calculates student grades. @@ -204,7 +204,7 @@ Algorithm: Calculate Student Grade ## Algorithm 6: Counter Patterns **Pseudocode:** -```lua +``` Algorithm: Different Counter Patterns 1. SET counter TO 1 2. SET even_counter TO 2 @@ -221,7 +221,7 @@ Algorithm: Different Counter Patterns 13. DISPLAY "Odd: " + odd_counter 14. SET odd_counter TO odd_counter + 2 15. END WHILE -```lua +``` **Your Task:** Create a Lua program that demonstrates different counting patterns. @@ -230,7 +230,7 @@ Algorithm: Different Counter Patterns ## Algorithm 7: Accumulator Pattern **Pseudocode:** -```lua +``` Algorithm: Calculate Statistics 1. SET sum TO 0 2. SET count TO 0 @@ -252,7 +252,7 @@ Algorithm: Calculate Statistics 18. DISPLAY "Count: " + count 19. DISPLAY "Product: " + product 20. DISPLAY "Average: " + average -```lua +``` **Your Task:** Create a Lua program that demonstrates accumulator patterns. @@ -308,7 +308,7 @@ Algorithm: Calculate Statistics ### Algorithm 1: Simple Variable Swapping -```lua +``` -- Algorithm: Swap Two Variables local first_number = 10 local second_number = 20 @@ -320,11 +320,11 @@ first_number = second_number second_number = temp print("After swap: first=" .. first_number .. ", second=" .. second_number) -```lua +``` ### Algorithm 2: Running Total Calculator -```lua +``` -- Algorithm: Calculate Running Total local total = 0 local count = 0 @@ -346,11 +346,11 @@ local average = total / count print("Total: " .. total) print("Count: " .. count) print("Average: " .. average) -```lua +``` ### Algorithm 3: Temperature Tracker -```lua +``` -- Algorithm: Track Temperature Readings local min_temp = 100 local max_temp = -100 @@ -381,11 +381,11 @@ if current_temp > max_temp then max_temp = current_temp end print("Current: " .. current_temp .. ", Min: " .. min_temp .. ", Max: " .. max_temp) -```lua +``` ### Algorithm 4: Account Balance Tracker -```lua +``` -- Algorithm: Track Bank Account Balance local account_balance = 1000 @@ -404,11 +404,11 @@ print("Balance after withdrawal: $" .. account_balance) transaction_amount = 150.25 account_balance = account_balance + transaction_amount print("Balance after deposit: $" .. account_balance) -```lua +``` ### Algorithm 5: Student Grade Calculator -```lua +``` -- Algorithm: Calculate Student Grade local total_points = 0 local possible_points = 0 @@ -445,11 +445,11 @@ print("Total Points: " .. total_points) print("Possible Points: " .. possible_points) print("Percentage: " .. percentage) print("Letter Grade: " .. letter_grade) -```lua +``` ### Algorithm 6: Counter Patterns -```lua +``` -- Algorithm: Different Counter Patterns local counter = 1 while counter <= 5 do @@ -468,11 +468,11 @@ while odd_counter <= 10 do print("Odd: " .. odd_counter) odd_counter = odd_counter + 2 end -```lua +``` ### Algorithm 7: Accumulator Pattern -```lua +``` -- Algorithm: Calculate Statistics local sum = 0 local count = 0 @@ -499,7 +499,7 @@ print("Sum: " .. sum) print("Count: " .. count) print("Product: " .. product) print("Average: " .. average) -```lua +``` ### Variable Translation Patterns @@ -524,7 +524,7 @@ print("Average: " .. average) --- - **Excellent work! You've mastered handling variables in pseudocode-to-code translation!** + **Excellent work! You've mastered handling variables in pseudocode-to-code translation!** *Next up: Mathematical operations in pseudocode!* @@ -544,40 +544,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```lua -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard lua conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/lua/stage-2/level-3/lesson.md b/lessons/lua/stage-2/level-3/lesson.md index 9482bff..f878c7c 100644 --- a/lessons/lua/stage-2/level-3/lesson.md +++ b/lessons/lua/stage-2/level-3/lesson.md @@ -26,36 +26,36 @@ Welcome to Level 3! Today we're focusing on mathematical operations in pseudocod Mathematical expressions in pseudocode follow standard notation: **Basic operations:** -```lua +``` SET result TO 5 + 3 SET result TO 10 - 4 SET result TO 6 * 7 SET result TO 15 / 3 SET remainder TO 17 MOD 5 -```lua +``` **Complex expressions:** -```lua +``` SET area TO length * width SET volume TO length * width * height SET average TO (num1 + num2 + num3) / 3 SET tax TO price * 0.08 SET discount TO original_price * discount_rate -```lua +``` **Order of operations:** -```lua +``` SET result TO 2 + 3 * 4 // result = 14 (not 20), multiplication first SET result TO (2 + 3) * 4 // result = 20, parentheses override SET result TO 10 / 2 + 3 // result = 8, division first -```lua +``` **Mathematical functions:** -```lua +``` SET result TO POWER(2, 3) // 2 to the power of 3 SET result TO SQRT(16) // square root of 16 SET result TO ROUND(3.7) // round to nearest integer -```lua +``` --- @@ -69,19 +69,19 @@ SET result TO ROUND(3.7) // round to nearest integer ### How to Run 1. **Run the code**: - ```bash + ``` lua hello.lua - ```lua + ``` **Expected output:** -```lua +``` Hello, World! -```lua +``` ## Algorithm 1: Complex Arithmetic Expression **Pseudocode:** -```lua +``` Algorithm: Evaluate Complex Expression 1. SET a TO 10 2. SET b TO 5 @@ -92,7 +92,7 @@ Algorithm: Evaluate Complex Expression 7. DISPLAY "Result without parentheses: " + result2 8. SET result3 TO ((a + b) * c - a) / c 9. DISPLAY "Result with different grouping: " + result3 -```lua +``` **Your Task:** Create a Lua program that evaluates complex arithmetic expressions. @@ -101,7 +101,7 @@ Algorithm: Evaluate Complex Expression ## Algorithm 2: Quadratic Formula Calculator **Pseudocode:** -```lua +``` Algorithm: Solve Quadratic Equation 1. SET a TO 1 2. SET b TO -5 @@ -112,7 +112,7 @@ Algorithm: Solve Quadratic Equation 7. SET root2 TO (-b - sqrt_discriminant) / (2 * a) 8. DISPLAY "Root 1: " + root1 9. DISPLAY "Root 2: " + root2 -```lua +``` **Your Task:** Create a Lua program that solves quadratic equations using the quadratic formula. @@ -121,7 +121,7 @@ Algorithm: Solve Quadratic Equation ## Algorithm 3: Compound Interest Calculator **Pseudocode:** -```lua +``` Algorithm: Calculate Compound Interest 1. SET principal TO 1000 2. SET rate TO 0.05 @@ -132,7 +132,7 @@ Algorithm: Calculate Compound Interest 7. DISPLAY "Principal: $" + principal 8. DISPLAY "Final Amount: $" + amount 9. DISPLAY "Interest Earned: $" + interest -```lua +``` **Your Task:** Create a Lua program that calculates compound interest. @@ -141,7 +141,7 @@ Algorithm: Calculate Compound Interest ## Algorithm 4: Geometric Calculations **Pseudocode:** -```lua +``` Algorithm: Calculate Geometric Properties 1. SET radius TO 5 2. SET side TO 4 @@ -155,7 +155,7 @@ Algorithm: Calculate Geometric Properties 10. DISPLAY "Circle - Area: " + circle_area + ", Circumference: " + circle_circumference 11. DISPLAY "Square - Area: " + square_area + ", Perimeter: " + square_perimeter 12. DISPLAY "Triangle - Area: " + triangle_area -```lua +``` **Your Task:** Create a Lua program that calculates geometric properties. @@ -164,7 +164,7 @@ Algorithm: Calculate Geometric Properties ## Algorithm 5: Physics Formula Calculator **Pseudocode:** -```lua +``` Algorithm: Physics Calculations 1. SET mass TO 5.5 2. SET velocity TO 10 @@ -178,7 +178,7 @@ Algorithm: Physics Calculations 10. DISPLAY "Force: " + force 11. DISPLAY "Distance: " + distance 12. DISPLAY "Momentum: " + momentum -```lua +``` **Your Task:** Create a Lua program that calculates physics formulas. @@ -187,7 +187,7 @@ Algorithm: Physics Calculations ## Algorithm 6: Temperature Conversion with Multiple Formulas **Pseudocode:** -```lua +``` Algorithm: Multiple Temperature Conversions 1. SET celsius TO 25 2. SET fahrenheit TO celsius * 9 / 5 + 32 @@ -199,7 +199,7 @@ Algorithm: Multiple Temperature Conversions 8. DISPLAY "Kelvin: " + kelvin 9. DISPLAY "F to C: " + celsius_from_f 10. DISPLAY "K to C: " + celsius_from_k -```lua +``` **Your Task:** Create a Lua program that performs multiple temperature conversions. @@ -208,7 +208,7 @@ Algorithm: Multiple Temperature Conversions ## Algorithm 7: Statistical Calculations **Pseudocode:** -```lua +``` Algorithm: Calculate Statistics for Three Numbers 1. SET num1 TO 10 2. SET num2 TO 20 @@ -225,7 +225,7 @@ Algorithm: Calculate Statistics for Three Numbers 13. DISPLAY "Range: " + range 14. DISPLAY "Variance: " + variance 15. DISPLAY "Standard Deviation: " + std_deviation -```lua +``` **Your Task:** Create a Lua program that calculates statistical measures. @@ -281,7 +281,7 @@ Algorithm: Calculate Statistics for Three Numbers ### Algorithm 1: Complex Arithmetic Expression -```lua +``` -- Algorithm: Evaluate Complex Expression local a = 10 local b = 5 @@ -295,11 +295,11 @@ print("Result without parentheses: " .. result2) local result3 = ((a + b) * c - a) / c print("Result with different grouping: " .. result3) -```lua +``` ### Algorithm 2: Quadratic Formula Calculator -```lua +``` -- Algorithm: Solve Quadratic Equation local a = 1 local b = -5 @@ -312,11 +312,11 @@ local root2 = (-b - sqrt_discriminant) / (2 * a) print("Root 1: " .. root1) print("Root 2: " .. root2) -```lua +``` ### Algorithm 3: Compound Interest Calculator -```lua +``` -- Algorithm: Calculate Compound Interest local principal = 1000 local rate = 0.05 @@ -329,11 +329,11 @@ local interest = amount - principal print("Principal: $" .. principal) print("Final Amount: $" .. string.format("%.2f", amount)) print("Interest Earned: $" .. string.format("%.2f", interest)) -```lua +``` ### Algorithm 4: Geometric Calculations -```lua +``` -- Algorithm: Calculate Geometric Properties local radius = 5 local side = 4 @@ -349,11 +349,11 @@ local triangle_area = 0.5 * base * height print("Circle - Area: " .. string.format("%.2f", circle_area) .. ", Circumference: " .. string.format("%.2f", circle_circumference)) print("Square - Area: " .. square_area .. ", Perimeter: " .. square_perimeter) print("Triangle - Area: " .. triangle_area) -```lua +``` ### Algorithm 5: Physics Formula Calculator -```lua +``` -- Algorithm: Physics Calculations local mass = 5.5 local velocity = 10 @@ -369,11 +369,11 @@ print("Kinetic Energy: " .. kinetic_energy) print("Force: " .. force) print("Distance: " .. distance) print("Momentum: " .. momentum) -```lua +``` ### Algorithm 6: Temperature Conversion with Multiple Formulas -```lua +``` -- Algorithm: Multiple Temperature Conversions local celsius = 25 local fahrenheit = celsius * 9 / 5 + 32 @@ -386,11 +386,11 @@ print("Fahrenheit: " .. fahrenheit) print("Kelvin: " .. kelvin) print("F to C: " .. celsius_from_f) print("K to C: " .. celsius_from_k) -```lua +``` ### Algorithm 7: Statistical Calculations -```lua +``` -- Algorithm: Calculate Statistics for Three Numbers local num1 = 10 local num2 = 20 @@ -409,7 +409,7 @@ print("Average: " .. average) print("Range: " .. range) print("Variance: " .. variance) print("Standard Deviation: " .. string.format("%.2f", std_deviation)) -```lua +``` ### Mathematical Operation Translation Patterns @@ -436,7 +436,7 @@ print("Standard Deviation: " .. string.format("%.2f", std_deviation)) --- - **Excellent work! You've mastered translating mathematical operations from pseudocode to Lua!** + **Excellent work! You've mastered translating mathematical operations from pseudocode to Lua!** *Next up: Input/Output operations in pseudocode!* @@ -456,40 +456,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```lua -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard lua conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/lua/stage-2/level-4/lesson.md b/lessons/lua/stage-2/level-4/lesson.md index 617836a..f5b71e3 100644 --- a/lessons/lua/stage-2/level-4/lesson.md +++ b/lessons/lua/stage-2/level-4/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Lua:** -```lua +``` ALGORITHM: Input/Output Algorithms BEGIN @@ -39,7 +39,7 @@ BEGIN // Translate step by step into Lua // Test with sample inputs END -```lua +``` **Implementation Steps:** 1. Analyze what the algorithm does @@ -54,14 +54,14 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` lua hello.lua - ```lua + ``` **Expected output:** -```lua +``` Hello, World! -```lua +``` ### How to Approach This @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in Lua: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```lua +``` PSEUDOCODE: READ number IF number > 0 THEN @@ -168,7 +168,7 @@ PSEUDOCODE: ELSE PRINT "Not positive" END IF -```lua +``` This becomes structured Lua code following the language syntax. @@ -211,40 +211,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```lua -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard lua conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/lua/stage-2/level-5/lesson.md b/lessons/lua/stage-2/level-5/lesson.md index 23fec46..62fe107 100644 --- a/lessons/lua/stage-2/level-5/lesson.md +++ b/lessons/lua/stage-2/level-5/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Lua:** -```lua +``` ALGORITHM: Decision Algorithms BEGIN @@ -39,7 +39,7 @@ BEGIN // Translate step by step into Lua // Test with sample inputs END -```lua +``` **Implementation Steps:** 1. Analyze what the algorithm does @@ -54,14 +54,14 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` lua hello.lua - ```lua + ``` **Expected output:** -```lua +``` Hello, World! -```lua +``` ### How to Approach This @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in Lua: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```lua +``` PSEUDOCODE: READ number IF number > 0 THEN @@ -168,7 +168,7 @@ PSEUDOCODE: ELSE PRINT "Not positive" END IF -```lua +``` This becomes structured Lua code following the language syntax. @@ -211,40 +211,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```lua -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard lua conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/lua/stage-2/level-6/lesson.md b/lessons/lua/stage-2/level-6/lesson.md index 794f039..a294dbc 100644 --- a/lessons/lua/stage-2/level-6/lesson.md +++ b/lessons/lua/stage-2/level-6/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Lua:** -```lua +``` ALGORITHM: Loop Algorithms BEGIN @@ -39,7 +39,7 @@ BEGIN // Translate step by step into Lua // Test with sample inputs END -```lua +``` **Implementation Steps:** 1. Analyze what the algorithm does @@ -54,14 +54,14 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` lua hello.lua - ```lua + ``` **Expected output:** -```lua +``` Hello, World! -```lua +``` ### How to Approach This @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in Lua: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```lua +``` PSEUDOCODE: READ number IF number > 0 THEN @@ -168,7 +168,7 @@ PSEUDOCODE: ELSE PRINT "Not positive" END IF -```lua +``` This becomes structured Lua code following the language syntax. @@ -211,40 +211,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```lua -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard lua conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/lua/stage-2/level-7/lesson.md b/lessons/lua/stage-2/level-7/lesson.md index cfce7b3..4552203 100644 --- a/lessons/lua/stage-2/level-7/lesson.md +++ b/lessons/lua/stage-2/level-7/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Lua:** -```lua +``` ALGORITHM: Function Design BEGIN @@ -39,7 +39,7 @@ BEGIN // Translate step by step into Lua // Test with sample inputs END -```lua +``` **Implementation Steps:** 1. Analyze what the algorithm does @@ -54,14 +54,14 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` lua hello.lua - ```lua + ``` **Expected output:** -```lua +``` Hello, World! -```lua +``` ### How to Approach This @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in Lua: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```lua +``` PSEUDOCODE: READ number IF number > 0 THEN @@ -168,7 +168,7 @@ PSEUDOCODE: ELSE PRINT "Not positive" END IF -```lua +``` This becomes structured Lua code following the language syntax. @@ -211,40 +211,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```lua -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard lua conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/lua/stage-3/level-1/lesson.md b/lessons/lua/stage-3/level-1/lesson.md index 92d8309..217b432 100644 --- a/lessons/lua/stage-3/level-1/lesson.md +++ b/lessons/lua/stage-3/level-1/lesson.md @@ -51,14 +51,14 @@ Simple Problem Analysis - Design an algorithm to solve this problem, then implem ### How to Run 1. **Run the code**: - ```bash + ``` lua hello.lua - ```lua + ``` **Expected output:** -```lua +``` Hello, World! -```lua +``` ### How to Approach This @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```lua +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -169,7 +169,7 @@ BEGIN - Step 3 4. Display results END -```lua +``` Then translate this directly to Lua code. @@ -212,40 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```lua -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard lua conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/lua/stage-3/level-2/lesson.md b/lessons/lua/stage-3/level-2/lesson.md index f06ce2b..50e08c6 100644 --- a/lessons/lua/stage-3/level-2/lesson.md +++ b/lessons/lua/stage-3/level-2/lesson.md @@ -51,14 +51,14 @@ Data Structure Planning - Design an algorithm to solve this problem, then implem ### How to Run 1. **Run the code**: - ```bash + ``` lua hello.lua - ```lua + ``` **Expected output:** -```lua +``` Hello, World! -```lua +``` ### How to Approach This @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```lua +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -169,7 +169,7 @@ BEGIN - Step 3 4. Display results END -```lua +``` Then translate this directly to Lua code. @@ -212,40 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```lua -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard lua conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/lua/stage-3/level-3/lesson.md b/lessons/lua/stage-3/level-3/lesson.md index bbf7d9a..62c6bf7 100644 --- a/lessons/lua/stage-3/level-3/lesson.md +++ b/lessons/lua/stage-3/level-3/lesson.md @@ -51,14 +51,14 @@ Mathematical Problems - Design an algorithm to solve this problem, then implemen ### How to Run 1. **Run the code**: - ```bash + ``` lua hello.lua - ```lua + ``` **Expected output:** -```lua +``` Hello, World! -```lua +``` ### How to Approach This @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```lua +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -169,7 +169,7 @@ BEGIN - Step 3 4. Display results END -```lua +``` Then translate this directly to Lua code. @@ -212,40 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```lua -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard lua conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/lua/stage-3/level-4/lesson.md b/lessons/lua/stage-3/level-4/lesson.md index b3ba4e2..90fb196 100644 --- a/lessons/lua/stage-3/level-4/lesson.md +++ b/lessons/lua/stage-3/level-4/lesson.md @@ -51,14 +51,14 @@ Text Processing Problems - Design an algorithm to solve this problem, then imple ### How to Run 1. **Run the code**: - ```bash + ``` lua hello.lua - ```lua + ``` **Expected output:** -```lua +``` Hello, World! -```lua +``` ### How to Approach This @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```lua +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -169,7 +169,7 @@ BEGIN - Step 3 4. Display results END -```lua +``` Then translate this directly to Lua code. @@ -212,40 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```lua -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard lua conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/lua/stage-3/level-5/lesson.md b/lessons/lua/stage-3/level-5/lesson.md index 29b5bf9..ae72f4e 100644 --- a/lessons/lua/stage-3/level-5/lesson.md +++ b/lessons/lua/stage-3/level-5/lesson.md @@ -51,14 +51,14 @@ Logic Problems - Design an algorithm to solve this problem, then implement it. ### How to Run 1. **Run the code**: - ```bash + ``` lua hello.lua - ```lua + ``` **Expected output:** -```lua +``` Hello, World! -```lua +``` ### How to Approach This @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```lua +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -169,7 +169,7 @@ BEGIN - Step 3 4. Display results END -```lua +``` Then translate this directly to Lua code. @@ -212,40 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```lua -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard lua conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/lua/stage-3/level-6/lesson.md b/lessons/lua/stage-3/level-6/lesson.md index 10598ad..41e95f2 100644 --- a/lessons/lua/stage-3/level-6/lesson.md +++ b/lessons/lua/stage-3/level-6/lesson.md @@ -51,14 +51,14 @@ Search Algorithms - Design an algorithm to solve this problem, then implement it ### How to Run 1. **Run the code**: - ```bash + ``` lua hello.lua - ```lua + ``` **Expected output:** -```lua +``` Hello, World! -```lua +``` ### How to Approach This @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```lua +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -169,7 +169,7 @@ BEGIN - Step 3 4. Display results END -```lua +``` Then translate this directly to Lua code. @@ -212,40 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```lua -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard lua conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/lua/stage-3/level-7/lesson.md b/lessons/lua/stage-3/level-7/lesson.md index 8d9f18a..f53b6c3 100644 --- a/lessons/lua/stage-3/level-7/lesson.md +++ b/lessons/lua/stage-3/level-7/lesson.md @@ -51,14 +51,14 @@ Sorting Algorithms - Design an algorithm to solve this problem, then implement i ### How to Run 1. **Run the code**: - ```bash + ``` lua hello.lua - ```lua + ``` **Expected output:** -```lua +``` Hello, World! -```lua +``` ### How to Approach This @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```lua +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -169,7 +169,7 @@ BEGIN - Step 3 4. Display results END -```lua +``` Then translate this directly to Lua code. @@ -212,40 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```lua -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard lua conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/lua/stage-4/level-1/lesson.md b/lessons/lua/stage-4/level-1/lesson.md index 53303bb..387eafd 100644 --- a/lessons/lua/stage-4/level-1/lesson.md +++ b/lessons/lua/stage-4/level-1/lesson.md @@ -51,14 +51,14 @@ Build a complete Calculator Application application that: ### How to Run 1. **Run the code**: - ```bash + ``` lua hello.lua - ```lua + ``` **Expected output:** -```lua +``` Hello, World! -```lua +``` ### How to Approach This @@ -158,13 +158,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```lua +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```lua +``` Build incrementally - get one feature working before adding the next. @@ -207,40 +207,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```lua -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard lua conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/lua/stage-4/level-2/lesson.md b/lessons/lua/stage-4/level-2/lesson.md index 90b9bed..4592198 100644 --- a/lessons/lua/stage-4/level-2/lesson.md +++ b/lessons/lua/stage-4/level-2/lesson.md @@ -51,14 +51,14 @@ Build a complete Text Analysis Tool application that: ### How to Run 1. **Run the code**: - ```bash + ``` lua hello.lua - ```lua + ``` **Expected output:** -```lua +``` Hello, World! -```lua +``` ### How to Approach This @@ -158,13 +158,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```lua +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```lua +``` Build incrementally - get one feature working before adding the next. @@ -207,40 +207,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```lua -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard lua conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/lua/stage-4/level-3/lesson.md b/lessons/lua/stage-4/level-3/lesson.md index 2040aa0..3d3dbf1 100644 --- a/lessons/lua/stage-4/level-3/lesson.md +++ b/lessons/lua/stage-4/level-3/lesson.md @@ -51,14 +51,14 @@ Build a complete Data Processing application that: ### How to Run 1. **Run the code**: - ```bash + ``` lua hello.lua - ```lua + ``` **Expected output:** -```lua +``` Hello, World! -```lua +``` ### How to Approach This @@ -158,13 +158,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```lua +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```lua +``` Build incrementally - get one feature working before adding the next. @@ -207,40 +207,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```lua -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard lua conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/lua/stage-4/level-4/lesson.md b/lessons/lua/stage-4/level-4/lesson.md index dfdbc0a..d3d21c6 100644 --- a/lessons/lua/stage-4/level-4/lesson.md +++ b/lessons/lua/stage-4/level-4/lesson.md @@ -51,14 +51,14 @@ Build a complete File Operations application that: ### How to Run 1. **Run the code**: - ```bash + ``` lua hello.lua - ```lua + ``` **Expected output:** -```lua +``` Hello, World! -```lua +``` ### How to Approach This @@ -158,13 +158,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```lua +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```lua +``` Build incrementally - get one feature working before adding the next. @@ -207,40 +207,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```lua -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard lua conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/lua/stage-4/level-5/lesson.md b/lessons/lua/stage-4/level-5/lesson.md index 57fabf7..51af759 100644 --- a/lessons/lua/stage-4/level-5/lesson.md +++ b/lessons/lua/stage-4/level-5/lesson.md @@ -51,14 +51,14 @@ Build a complete API Integration application that: ### How to Run 1. **Run the code**: - ```bash + ``` lua hello.lua - ```lua + ``` **Expected output:** -```lua +``` Hello, World! -```lua +``` ### How to Approach This @@ -158,13 +158,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```lua +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```lua +``` Build incrementally - get one feature working before adding the next. @@ -207,40 +207,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```lua -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard lua conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/lua/stage-4/level-6/lesson.md b/lessons/lua/stage-4/level-6/lesson.md index ef7235c..1f4efcc 100644 --- a/lessons/lua/stage-4/level-6/lesson.md +++ b/lessons/lua/stage-4/level-6/lesson.md @@ -51,14 +51,14 @@ Build a complete Database Operations application that: ### How to Run 1. **Run the code**: - ```bash + ``` lua hello.lua - ```lua + ``` **Expected output:** -```lua +``` Hello, World! -```lua +``` ### How to Approach This @@ -158,13 +158,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```lua +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```lua +``` Build incrementally - get one feature working before adding the next. @@ -207,40 +207,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```lua -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard lua conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/lua/stage-4/level-7/lesson.md b/lessons/lua/stage-4/level-7/lesson.md index 6814dae..45b7456 100644 --- a/lessons/lua/stage-4/level-7/lesson.md +++ b/lessons/lua/stage-4/level-7/lesson.md @@ -51,14 +51,14 @@ Build a complete Complete Application application that: ### How to Run 1. **Run the code**: - ```bash + ``` lua hello.lua - ```lua + ``` **Expected output:** -```lua +``` Hello, World! -```lua +``` ### How to Approach This @@ -158,13 +158,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```lua +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```lua +``` Build incrementally - get one feature working before adding the next. @@ -207,40 +207,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```lua -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard lua conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/lua/stage-5/level-1/lesson.md b/lessons/lua/stage-5/level-1/lesson.md index 7459bf4..cf60f65 100644 --- a/lessons/lua/stage-5/level-1/lesson.md +++ b/lessons/lua/stage-5/level-1/lesson.md @@ -58,14 +58,14 @@ Create a production-ready Web Scraper using Lua with: ### How to Run 1. **Run the code**: - ```bash + ``` lua hello.lua - ```lua + ``` **Expected output:** -```lua +``` Hello, World! -```lua +``` ### How to Approach This @@ -222,40 +222,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```lua -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard lua conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/lua/stage-5/level-2/lesson.md b/lessons/lua/stage-5/level-2/lesson.md index bdf08b7..4372cdd 100644 --- a/lessons/lua/stage-5/level-2/lesson.md +++ b/lessons/lua/stage-5/level-2/lesson.md @@ -58,14 +58,14 @@ Create a production-ready CLI Tool using Lua with: ### How to Run 1. **Run the code**: - ```bash + ``` lua hello.lua - ```lua + ``` **Expected output:** -```lua +``` Hello, World! -```lua +``` ### How to Approach This @@ -222,40 +222,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```lua -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard lua conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/lua/stage-5/level-3/lesson.md b/lessons/lua/stage-5/level-3/lesson.md index a58f469..4d943f3 100644 --- a/lessons/lua/stage-5/level-3/lesson.md +++ b/lessons/lua/stage-5/level-3/lesson.md @@ -58,14 +58,14 @@ Create a production-ready REST API using Lua with: ### How to Run 1. **Run the code**: - ```bash + ``` lua hello.lua - ```lua + ``` **Expected output:** -```lua +``` Hello, World! -```lua +``` ### How to Approach This @@ -222,40 +222,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```lua -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard lua conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/lua/stage-5/level-4/lesson.md b/lessons/lua/stage-5/level-4/lesson.md index 2a474a3..11977a3 100644 --- a/lessons/lua/stage-5/level-4/lesson.md +++ b/lessons/lua/stage-5/level-4/lesson.md @@ -58,14 +58,14 @@ Create a production-ready Data Visualization using Lua with: ### How to Run 1. **Run the code**: - ```bash + ``` lua hello.lua - ```lua + ``` **Expected output:** -```lua +``` Hello, World! -```lua +``` ### How to Approach This @@ -222,40 +222,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```lua -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard lua conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/lua/stage-5/level-5/lesson.md b/lessons/lua/stage-5/level-5/lesson.md index 36fa8c3..067d497 100644 --- a/lessons/lua/stage-5/level-5/lesson.md +++ b/lessons/lua/stage-5/level-5/lesson.md @@ -58,14 +58,14 @@ Create a production-ready Automated Testing using Lua with: ### How to Run 1. **Run the code**: - ```bash + ``` lua hello.lua - ```lua + ``` **Expected output:** -```lua +``` Hello, World! -```lua +``` ### How to Approach This @@ -222,40 +222,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```lua -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard lua conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/lua/stage-5/level-6/lesson.md b/lessons/lua/stage-5/level-6/lesson.md index 444e53e..db7795b 100644 --- a/lessons/lua/stage-5/level-6/lesson.md +++ b/lessons/lua/stage-5/level-6/lesson.md @@ -58,14 +58,14 @@ Create a production-ready Performance Optimization using Lua with: ### How to Run 1. **Run the code**: - ```bash + ``` lua hello.lua - ```lua + ``` **Expected output:** -```lua +``` Hello, World! -```lua +``` ### How to Approach This @@ -222,40 +222,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```lua -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard lua conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/lua/stage-5/level-7/lesson.md b/lessons/lua/stage-5/level-7/lesson.md index c496d57..18cc817 100644 --- a/lessons/lua/stage-5/level-7/lesson.md +++ b/lessons/lua/stage-5/level-7/lesson.md @@ -58,14 +58,14 @@ Create a production-ready Final Capstone Project using Lua with: ### How to Run 1. **Run the code**: - ```bash + ``` lua hello.lua - ```lua + ``` **Expected output:** -```lua +``` Hello, World! -```lua +``` ### How to Approach This @@ -222,40 +222,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```lua -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard lua conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/nosql/stage-1/level-1/lesson.md b/lessons/nosql/stage-1/level-1/lesson.md index d676075..c78a8f9 100644 --- a/lessons/nosql/stage-1/level-1/lesson.md +++ b/lessons/nosql/stage-1/level-1/lesson.md @@ -23,7 +23,7 @@ Welcome to your first MongoDB (NoSQL) program! Today, you'll create and run your **Copy the following code EXACTLY as shown below into `main.js`** -```javascript +``` // MongoDB JavaScript shell script print("Hello, World!"); ``` @@ -33,12 +33,12 @@ print("Hello, World!"); ### How to Run **Method 1 (Vim - Recommended):** -```javascript +``` r ``` **Method 2 (Terminal):** -```bash +``` mongo < script.js ``` @@ -92,44 +92,25 @@ You just created a real MongoDB (NoSQL) program! Here's what makes it work: --- -## ANSWER KEY (No peeking until you've tried!) - -### Code Breakdown - -The code you copied demonstrates fundamental MongoDB (NoSQL) concepts: - -**Key Components:** -- Syntax rules specific to MongoDB (NoSQL) -- How data is stored and manipulated -- Input/output operations -- Program flow and structure +## ANSWER KEY (No cheating until you've tried!) -### Common Errors & Solutions +### Solution -| Error | Cause | Solution | -|-------|-------|----------| -| Syntax error | Typo in code | Double-check spelling and punctuation | -| Runtime error | Code runs but crashes | Check your logic and data types | -| Unexpected output | Logic error | Review your algorithm step-by-step | +``` +// MongoDB JavaScript shell script +print("Hello, World!"); +``` -### Bonus Knowledge +### Explanation -- MongoDB (NoSQL) has a rich ecosystem of libraries and tools -- Understanding these basics prepares you for advanced topics -- Practice is key - try writing similar programs from scratch -- Every expert programmer started exactly where you are now! +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -### Real-World Applications +### Success Criteria -This concept is used in: -1. Professional software development -2. Web applications and mobile apps -3. Data analysis and scientific computing -4. Automation and scripting -5. Game development +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -**Excellent work! You've mastered a fundamental concept!** - -*Ready for the next challenge? Keep going!* +**Great job! You've completed this lesson!** diff --git a/lessons/nosql/stage-1/level-2/lesson.md b/lessons/nosql/stage-1/level-2/lesson.md index cf8ce2c..1185c5e 100644 --- a/lessons/nosql/stage-1/level-2/lesson.md +++ b/lessons/nosql/stage-1/level-2/lesson.md @@ -23,7 +23,7 @@ Learn how to store and work with different types of data in MongoDB (NoSQL). **Copy the following code EXACTLY as shown below into `main.js`** -```javascript +``` // MongoDB document with variables db.test.insertOne({ name: "Alex", @@ -44,12 +44,12 @@ print("Price: $" + doc.price.toFixed(2)); ### How to Run **Method 1 (Vim - Recommended):** -```javascript +``` r ``` **Method 2 (Terminal):** -```bash +``` mongo < script.js ``` @@ -105,44 +105,36 @@ You just created a real MongoDB (NoSQL) program! Here's what makes it work: --- -## ANSWER KEY (No peeking until you've tried!) - -### Code Breakdown - -The code you copied demonstrates fundamental MongoDB (NoSQL) concepts: +## ANSWER KEY (No cheating until you've tried!) -**Key Components:** -- Syntax rules specific to MongoDB (NoSQL) -- How data is stored and manipulated -- Input/output operations -- Program flow and structure +### Solution -### Common Errors & Solutions +``` +// MongoDB document with variables +db.test.insertOne({ + name: "Alex", + age: 25, + score: 100, + price: 29.99 +}); -| Error | Cause | Solution | -|-------|-------|----------| -| Syntax error | Typo in code | Double-check spelling and punctuation | -| Runtime error | Code runs but crashes | Check your logic and data types | -| Unexpected output | Logic error | Review your algorithm step-by-step | +// Display +var doc = db.test.findOne(); +print("Name: " + doc.name); +print("Age: " + doc.age); +print("Price: $" + doc.price.toFixed(2)); +``` -### Bonus Knowledge +### Explanation -- MongoDB (NoSQL) has a rich ecosystem of libraries and tools -- Understanding these basics prepares you for advanced topics -- Practice is key - try writing similar programs from scratch -- Every expert programmer started exactly where you are now! +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -### Real-World Applications +### Success Criteria -This concept is used in: -1. Professional software development -2. Web applications and mobile apps -3. Data analysis and scientific computing -4. Automation and scripting -5. Game development +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -**Excellent work! You've mastered a fundamental concept!** - -*Ready for the next challenge? Keep going!* +**Great job! You've completed this lesson!** diff --git a/lessons/nosql/stage-1/level-3/lesson.md b/lessons/nosql/stage-1/level-3/lesson.md index 232f16c..e644bcd 100644 --- a/lessons/nosql/stage-1/level-3/lesson.md +++ b/lessons/nosql/stage-1/level-3/lesson.md @@ -23,7 +23,7 @@ Master arithmetic operations and use MongoDB (NoSQL) as your powerful calculator **Copy the following code EXACTLY as shown below into `main.js`** -```javascript +``` // Math operations in MongoDB var a = 10; var b = 3; @@ -40,12 +40,12 @@ print("Modulus: " + (a % b)); ### How to Run **Method 1 (Vim - Recommended):** -```javascript +``` r ``` **Method 2 (Terminal):** -```bash +``` mongo < script.js ``` @@ -102,44 +102,32 @@ You just created a real MongoDB (NoSQL) program! Here's what makes it work: --- -## ANSWER KEY (No peeking until you've tried!) - -### Code Breakdown +## ANSWER KEY (No cheating until you've tried!) -The code you copied demonstrates fundamental MongoDB (NoSQL) concepts: +### Solution -**Key Components:** -- Syntax rules specific to MongoDB (NoSQL) -- How data is stored and manipulated -- Input/output operations -- Program flow and structure - -### Common Errors & Solutions +``` +// Math operations in MongoDB +var a = 10; +var b = 3; -| Error | Cause | Solution | -|-------|-------|----------| -| Syntax error | Typo in code | Double-check spelling and punctuation | -| Runtime error | Code runs but crashes | Check your logic and data types | -| Unexpected output | Logic error | Review your algorithm step-by-step | +print("Addition: " + (a + b)); +print("Subtraction: " + (a - b)); +print("Multiplication: " + (a * b)); +print("Division: " + (a / b)); +print("Modulus: " + (a % b)); +``` -### Bonus Knowledge +### Explanation -- MongoDB (NoSQL) has a rich ecosystem of libraries and tools -- Understanding these basics prepares you for advanced topics -- Practice is key - try writing similar programs from scratch -- Every expert programmer started exactly where you are now! +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -### Real-World Applications +### Success Criteria -This concept is used in: -1. Professional software development -2. Web applications and mobile apps -3. Data analysis and scientific computing -4. Automation and scripting -5. Game development +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -**Excellent work! You've mastered a fundamental concept!** - -*Ready for the next challenge? Keep going!* +**Great job! You've completed this lesson!** diff --git a/lessons/nosql/stage-1/level-4/lesson.md b/lessons/nosql/stage-1/level-4/lesson.md index 06b2a0f..2657c86 100644 --- a/lessons/nosql/stage-1/level-4/lesson.md +++ b/lessons/nosql/stage-1/level-4/lesson.md @@ -23,7 +23,7 @@ Make your programs interactive by reading input from users. **Copy the following code EXACTLY as shown below into `main.js`** -```javascript +``` // MongoDB aggregation example db.students.insertMany([ { name: "Alice", score: 95 }, @@ -43,12 +43,12 @@ students.forEach(function(student) { ### How to Run **Method 1 (Vim - Recommended):** -```javascript +``` r ``` **Method 2 (Terminal):** -```bash +``` mongo < script.js ``` @@ -102,44 +102,35 @@ You just created a real MongoDB (NoSQL) program! Here's what makes it work: --- -## ANSWER KEY (No peeking until you've tried!) - -### Code Breakdown - -The code you copied demonstrates fundamental MongoDB (NoSQL) concepts: +## ANSWER KEY (No cheating until you've tried!) -**Key Components:** -- Syntax rules specific to MongoDB (NoSQL) -- How data is stored and manipulated -- Input/output operations -- Program flow and structure +### Solution -### Common Errors & Solutions +``` +// MongoDB aggregation example +db.students.insertMany([ + { name: "Alice", score: 95 }, + { name: "Bob", score: 87 }, + { name: "Carol", score: 92 } +]); -| Error | Cause | Solution | -|-------|-------|----------| -| Syntax error | Typo in code | Double-check spelling and punctuation | -| Runtime error | Code runs but crashes | Check your logic and data types | -| Unexpected output | Logic error | Review your algorithm step-by-step | +// Query +var students = db.students.find(); +students.forEach(function(student) { + print("Student: " + student.name + ", Score: " + student.score); +}); +``` -### Bonus Knowledge +### Explanation -- MongoDB (NoSQL) has a rich ecosystem of libraries and tools -- Understanding these basics prepares you for advanced topics -- Practice is key - try writing similar programs from scratch -- Every expert programmer started exactly where you are now! +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -### Real-World Applications +### Success Criteria -This concept is used in: -1. Professional software development -2. Web applications and mobile apps -3. Data analysis and scientific computing -4. Automation and scripting -5. Game development +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -**Excellent work! You've mastered a fundamental concept!** - -*Ready for the next challenge? Keep going!* +**Great job! You've completed this lesson!** diff --git a/lessons/nosql/stage-1/level-5/lesson.md b/lessons/nosql/stage-1/level-5/lesson.md index b6fa285..18f8e0b 100644 --- a/lessons/nosql/stage-1/level-5/lesson.md +++ b/lessons/nosql/stage-1/level-5/lesson.md @@ -23,7 +23,7 @@ Add decision-making to your programs with if/else statements. **Copy the following code EXACTLY as shown below into `main.js`** -```javascript +``` // Conditional queries in MongoDB db.students.insertMany([ { name: "Alice", score: 95 }, @@ -50,12 +50,12 @@ passing.forEach(function(s) { ### How to Run **Method 1 (Vim - Recommended):** -```javascript +``` r ``` **Method 2 (Terminal):** -```bash +``` mongo < script.js ``` @@ -109,44 +109,42 @@ You just created a real MongoDB (NoSQL) program! Here's what makes it work: --- -## ANSWER KEY (No peeking until you've tried!) +## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -The code you copied demonstrates fundamental MongoDB (NoSQL) concepts: - -**Key Components:** -- Syntax rules specific to MongoDB (NoSQL) -- How data is stored and manipulated -- Input/output operations -- Program flow and structure +``` +// Conditional queries in MongoDB +db.students.insertMany([ + { name: "Alice", score: 95 }, + { name: "Bob", score: 75 }, + { name: "Carol", score: 55 } +]); -### Common Errors & Solutions +// Find students by grade +var excellent = db.students.find({ score: { $gte: 90 } }); +print("Excellent students (A):"); +excellent.forEach(function(s) { + print(" " + s.name + ": " + s.score); +}); -| Error | Cause | Solution | -|-------|-------|----------| -| Syntax error | Typo in code | Double-check spelling and punctuation | -| Runtime error | Code runs but crashes | Check your logic and data types | -| Unexpected output | Logic error | Review your algorithm step-by-step | +var passing = db.students.find({ score: { $gte: 70, $lt: 90 } }); +print("\nPassing students (B/C):"); +passing.forEach(function(s) { + print(" " + s.name + ": " + s.score); +}); +``` -### Bonus Knowledge +### Explanation -- MongoDB (NoSQL) has a rich ecosystem of libraries and tools -- Understanding these basics prepares you for advanced topics -- Practice is key - try writing similar programs from scratch -- Every expert programmer started exactly where you are now! +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -### Real-World Applications +### Success Criteria -This concept is used in: -1. Professional software development -2. Web applications and mobile apps -3. Data analysis and scientific computing -4. Automation and scripting -5. Game development +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -**Excellent work! You've mastered a fundamental concept!** - -*Ready for the next challenge? Keep going!* +**Great job! You've completed this lesson!** diff --git a/lessons/nosql/stage-1/level-6/lesson.md b/lessons/nosql/stage-1/level-6/lesson.md index 196be37..1f32d2d 100644 --- a/lessons/nosql/stage-1/level-6/lesson.md +++ b/lessons/nosql/stage-1/level-6/lesson.md @@ -23,7 +23,7 @@ Learn to repeat actions efficiently using loops. **Copy the following code EXACTLY as shown below into `main.js`** -```javascript +``` // Loop operations in MongoDB print("Creating documents 1-10:"); for (var i = 1; i <= 10; i++) { @@ -50,12 +50,12 @@ for (var i = 1; i <= 10; i++) { ### How to Run **Method 1 (Vim - Recommended):** -```javascript +``` r ``` **Method 2 (Terminal):** -```bash +``` mongo < script.js ``` @@ -109,44 +109,42 @@ You just created a real MongoDB (NoSQL) program! Here's what makes it work: --- -## ANSWER KEY (No peeking until you've tried!) +## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -The code you copied demonstrates fundamental MongoDB (NoSQL) concepts: - -**Key Components:** -- Syntax rules specific to MongoDB (NoSQL) -- How data is stored and manipulated -- Input/output operations -- Program flow and structure +``` +// Loop operations in MongoDB +print("Creating documents 1-10:"); +for (var i = 1; i <= 10; i++) { + db.numbers.insertOne({ value: i }); +} -### Common Errors & Solutions +// Read and display +var docs = db.numbers.find().sort({ value: 1 }); +print("\nStored numbers:"); +docs.forEach(function(doc) { + print(doc.value); +}); -| Error | Cause | Solution | -|-------|-------|----------| -| Syntax error | Typo in code | Double-check spelling and punctuation | -| Runtime error | Code runs but crashes | Check your logic and data types | -| Unexpected output | Logic error | Review your algorithm step-by-step | +// Multiplication table +var num = 7; +print("\n" + num + " times table:"); +for (var i = 1; i <= 10; i++) { + print(num + " × " + i + " = " + (num * i)); +} +``` -### Bonus Knowledge +### Explanation -- MongoDB (NoSQL) has a rich ecosystem of libraries and tools -- Understanding these basics prepares you for advanced topics -- Practice is key - try writing similar programs from scratch -- Every expert programmer started exactly where you are now! +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -### Real-World Applications +### Success Criteria -This concept is used in: -1. Professional software development -2. Web applications and mobile apps -3. Data analysis and scientific computing -4. Automation and scripting -5. Game development +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -**Excellent work! You've mastered a fundamental concept!** - -*Ready for the next challenge? Keep going!* +**Great job! You've completed this lesson!** diff --git a/lessons/nosql/stage-1/level-7/lesson.md b/lessons/nosql/stage-1/level-7/lesson.md index 2f90fe9..8096020 100644 --- a/lessons/nosql/stage-1/level-7/lesson.md +++ b/lessons/nosql/stage-1/level-7/lesson.md @@ -23,7 +23,7 @@ Organize your code into reusable functions/methods. **Copy the following code EXACTLY as shown below into `main.js`** -```javascript +``` // Functions in MongoDB JavaScript function greet(name) { print("Hello, " + name + "!"); @@ -55,12 +55,12 @@ print("5! = " + factorial(5)); ### How to Run **Method 1 (Vim - Recommended):** -```javascript +``` r ``` **Method 2 (Terminal):** -```bash +``` mongo < script.js ``` @@ -114,44 +114,47 @@ You just created a real MongoDB (NoSQL) program! Here's what makes it work: --- -## ANSWER KEY (No peeking until you've tried!) +## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -The code you copied demonstrates fundamental MongoDB (NoSQL) concepts: +``` +// Functions in MongoDB JavaScript +function greet(name) { + print("Hello, " + name + "!"); +} -**Key Components:** -- Syntax rules specific to MongoDB (NoSQL) -- How data is stored and manipulated -- Input/output operations -- Program flow and structure +function add(a, b) { + return a + b; +} -### Common Errors & Solutions +function factorial(n) { + var result = 1; + for (var i = 1; i <= n; i++) { + result *= i; + } + return result; +} -| Error | Cause | Solution | -|-------|-------|----------| -| Syntax error | Typo in code | Double-check spelling and punctuation | -| Runtime error | Code runs but crashes | Check your logic and data types | -| Unexpected output | Logic error | Review your algorithm step-by-step | +greet("Alice"); +greet("Bob"); -### Bonus Knowledge +var sum = add(5, 3); +print("5 + 3 = " + sum); + +print("5! = " + factorial(5)); +``` -- MongoDB (NoSQL) has a rich ecosystem of libraries and tools -- Understanding these basics prepares you for advanced topics -- Practice is key - try writing similar programs from scratch -- Every expert programmer started exactly where you are now! +### Explanation -### Real-World Applications +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -This concept is used in: -1. Professional software development -2. Web applications and mobile apps -3. Data analysis and scientific computing -4. Automation and scripting -5. Game development +### Success Criteria ---- +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does -**Excellent work! You've mastered a fundamental concept!** +--- -*Ready for the next challenge? Keep going!* +**Great job! You've completed this lesson!** diff --git a/lessons/nosql/stage-2/level-1/lesson.md b/lessons/nosql/stage-2/level-1/lesson.md index 0948144..220074e 100644 --- a/lessons/nosql/stage-2/level-1/lesson.md +++ b/lessons/nosql/stage-2/level-1/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in MongoDB:** -```javascript +``` ALGORITHM: Basic Algorithm Translation BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` mongo hello.js ``` @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in MongoDB: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```javascript +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/nosql/stage-2/level-2/lesson.md b/lessons/nosql/stage-2/level-2/lesson.md index e9b540b..0c6a643 100644 --- a/lessons/nosql/stage-2/level-2/lesson.md +++ b/lessons/nosql/stage-2/level-2/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in MongoDB:** -```javascript +``` ALGORITHM: Variables in Algorithms BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` mongo hello.js ``` @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in MongoDB: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```javascript +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/nosql/stage-2/level-3/lesson.md b/lessons/nosql/stage-2/level-3/lesson.md index 0f49577..b185a46 100644 --- a/lessons/nosql/stage-2/level-3/lesson.md +++ b/lessons/nosql/stage-2/level-3/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in MongoDB:** -```javascript +``` ALGORITHM: Mathematical Algorithms BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` mongo hello.js ``` @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in MongoDB: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```javascript +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/nosql/stage-2/level-4/lesson.md b/lessons/nosql/stage-2/level-4/lesson.md index da1b161..068331e 100644 --- a/lessons/nosql/stage-2/level-4/lesson.md +++ b/lessons/nosql/stage-2/level-4/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in MongoDB:** -```javascript +``` ALGORITHM: Input/Output Algorithms BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` mongo hello.js ``` @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in MongoDB: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```javascript +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/nosql/stage-2/level-5/lesson.md b/lessons/nosql/stage-2/level-5/lesson.md index 7895f06..457f644 100644 --- a/lessons/nosql/stage-2/level-5/lesson.md +++ b/lessons/nosql/stage-2/level-5/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in MongoDB:** -```javascript +``` ALGORITHM: Decision Algorithms BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` mongo hello.js ``` @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in MongoDB: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```javascript +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/nosql/stage-2/level-6/lesson.md b/lessons/nosql/stage-2/level-6/lesson.md index b648eb7..a5c8fc0 100644 --- a/lessons/nosql/stage-2/level-6/lesson.md +++ b/lessons/nosql/stage-2/level-6/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in MongoDB:** -```javascript +``` ALGORITHM: Loop Algorithms BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` mongo hello.js ``` @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in MongoDB: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```javascript +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/nosql/stage-2/level-7/lesson.md b/lessons/nosql/stage-2/level-7/lesson.md index 6569079..0822a5c 100644 --- a/lessons/nosql/stage-2/level-7/lesson.md +++ b/lessons/nosql/stage-2/level-7/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in MongoDB:** -```javascript +``` ALGORITHM: Function Design BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` mongo hello.js ``` @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in MongoDB: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```javascript +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/nosql/stage-3/level-1/lesson.md b/lessons/nosql/stage-3/level-1/lesson.md index 648b969..37512b5 100644 --- a/lessons/nosql/stage-3/level-1/lesson.md +++ b/lessons/nosql/stage-3/level-1/lesson.md @@ -51,7 +51,7 @@ Simple Problem Analysis - Design an algorithm to solve this problem, then implem ### How to Run 1. **Run the code**: - ```bash + ``` mongo hello.js ``` @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```javascript +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/nosql/stage-3/level-2/lesson.md b/lessons/nosql/stage-3/level-2/lesson.md index 43e505e..69efe3d 100644 --- a/lessons/nosql/stage-3/level-2/lesson.md +++ b/lessons/nosql/stage-3/level-2/lesson.md @@ -51,7 +51,7 @@ Data Structure Planning - Design an algorithm to solve this problem, then implem ### How to Run 1. **Run the code**: - ```bash + ``` mongo hello.js ``` @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```javascript +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/nosql/stage-3/level-3/lesson.md b/lessons/nosql/stage-3/level-3/lesson.md index 260fae1..ec158f7 100644 --- a/lessons/nosql/stage-3/level-3/lesson.md +++ b/lessons/nosql/stage-3/level-3/lesson.md @@ -51,7 +51,7 @@ Mathematical Problems - Design an algorithm to solve this problem, then implemen ### How to Run 1. **Run the code**: - ```bash + ``` mongo hello.js ``` @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```javascript +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/nosql/stage-3/level-4/lesson.md b/lessons/nosql/stage-3/level-4/lesson.md index 056df1e..cb1bf5a 100644 --- a/lessons/nosql/stage-3/level-4/lesson.md +++ b/lessons/nosql/stage-3/level-4/lesson.md @@ -51,7 +51,7 @@ Text Processing Problems - Design an algorithm to solve this problem, then imple ### How to Run 1. **Run the code**: - ```bash + ``` mongo hello.js ``` @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```javascript +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/nosql/stage-3/level-5/lesson.md b/lessons/nosql/stage-3/level-5/lesson.md index 9887a66..85fdbf5 100644 --- a/lessons/nosql/stage-3/level-5/lesson.md +++ b/lessons/nosql/stage-3/level-5/lesson.md @@ -51,7 +51,7 @@ Logic Problems - Design an algorithm to solve this problem, then implement it. ### How to Run 1. **Run the code**: - ```bash + ``` mongo hello.js ``` @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```javascript +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/nosql/stage-3/level-6/lesson.md b/lessons/nosql/stage-3/level-6/lesson.md index 7656fc0..5bcec28 100644 --- a/lessons/nosql/stage-3/level-6/lesson.md +++ b/lessons/nosql/stage-3/level-6/lesson.md @@ -51,7 +51,7 @@ Search Algorithms - Design an algorithm to solve this problem, then implement it ### How to Run 1. **Run the code**: - ```bash + ``` mongo hello.js ``` @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```javascript +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/nosql/stage-3/level-7/lesson.md b/lessons/nosql/stage-3/level-7/lesson.md index fd47776..ef5ea96 100644 --- a/lessons/nosql/stage-3/level-7/lesson.md +++ b/lessons/nosql/stage-3/level-7/lesson.md @@ -51,7 +51,7 @@ Sorting Algorithms - Design an algorithm to solve this problem, then implement i ### How to Run 1. **Run the code**: - ```bash + ``` mongo hello.js ``` @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```javascript +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/nosql/stage-4/level-1/lesson.md b/lessons/nosql/stage-4/level-1/lesson.md index 3fd05a0..f7ca0f8 100644 --- a/lessons/nosql/stage-4/level-1/lesson.md +++ b/lessons/nosql/stage-4/level-1/lesson.md @@ -51,7 +51,7 @@ Build a complete Calculator Application application that: ### How to Run 1. **Run the code**: - ```bash + ``` mongo hello.js ``` @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```javascript +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/nosql/stage-4/level-2/lesson.md b/lessons/nosql/stage-4/level-2/lesson.md index 366889e..b0c1fe8 100644 --- a/lessons/nosql/stage-4/level-2/lesson.md +++ b/lessons/nosql/stage-4/level-2/lesson.md @@ -51,7 +51,7 @@ Build a complete Text Analysis Tool application that: ### How to Run 1. **Run the code**: - ```bash + ``` mongo hello.js ``` @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```javascript +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/nosql/stage-4/level-3/lesson.md b/lessons/nosql/stage-4/level-3/lesson.md index 1f3eb06..541e4e6 100644 --- a/lessons/nosql/stage-4/level-3/lesson.md +++ b/lessons/nosql/stage-4/level-3/lesson.md @@ -51,7 +51,7 @@ Build a complete Data Processing application that: ### How to Run 1. **Run the code**: - ```bash + ``` mongo hello.js ``` @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```javascript +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/nosql/stage-4/level-4/lesson.md b/lessons/nosql/stage-4/level-4/lesson.md index fbb62e4..4ec5519 100644 --- a/lessons/nosql/stage-4/level-4/lesson.md +++ b/lessons/nosql/stage-4/level-4/lesson.md @@ -51,7 +51,7 @@ Build a complete File Operations application that: ### How to Run 1. **Run the code**: - ```bash + ``` mongo hello.js ``` @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```javascript +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/nosql/stage-4/level-5/lesson.md b/lessons/nosql/stage-4/level-5/lesson.md index fa9d15c..197d998 100644 --- a/lessons/nosql/stage-4/level-5/lesson.md +++ b/lessons/nosql/stage-4/level-5/lesson.md @@ -51,7 +51,7 @@ Build a complete API Integration application that: ### How to Run 1. **Run the code**: - ```bash + ``` mongo hello.js ``` @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```javascript +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/nosql/stage-4/level-6/lesson.md b/lessons/nosql/stage-4/level-6/lesson.md index 3c5d079..405870f 100644 --- a/lessons/nosql/stage-4/level-6/lesson.md +++ b/lessons/nosql/stage-4/level-6/lesson.md @@ -51,7 +51,7 @@ Build a complete Database Operations application that: ### How to Run 1. **Run the code**: - ```bash + ``` mongo hello.js ``` @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```javascript +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/nosql/stage-4/level-7/lesson.md b/lessons/nosql/stage-4/level-7/lesson.md index 68d9fe8..829d7d9 100644 --- a/lessons/nosql/stage-4/level-7/lesson.md +++ b/lessons/nosql/stage-4/level-7/lesson.md @@ -51,7 +51,7 @@ Build a complete Complete Application application that: ### How to Run 1. **Run the code**: - ```bash + ``` mongo hello.js ``` @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```javascript +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/nosql/stage-5/level-1/lesson.md b/lessons/nosql/stage-5/level-1/lesson.md index 4436ebf..0cf50cd 100644 --- a/lessons/nosql/stage-5/level-1/lesson.md +++ b/lessons/nosql/stage-5/level-1/lesson.md @@ -242,7 +242,7 @@ Follow these stages: **Your architecture will depend on your chosen project, but should include:** -```nosql +``` // Main program structure // - Data definitions // - Core functions diff --git a/lessons/nosql/stage-5/level-2/lesson.md b/lessons/nosql/stage-5/level-2/lesson.md index 1f784f7..c6d54c0 100644 --- a/lessons/nosql/stage-5/level-2/lesson.md +++ b/lessons/nosql/stage-5/level-2/lesson.md @@ -233,7 +233,7 @@ Follow these stages: **Your architecture will depend on your chosen project, but should include:** -```nosql +``` // Main program structure // - Data definitions // - Core functions diff --git a/lessons/nosql/stage-5/level-3/lesson.md b/lessons/nosql/stage-5/level-3/lesson.md index 0b7cee2..f2291cb 100644 --- a/lessons/nosql/stage-5/level-3/lesson.md +++ b/lessons/nosql/stage-5/level-3/lesson.md @@ -238,7 +238,7 @@ Follow these stages: **Your architecture will depend on your chosen project, but should include:** -```nosql +``` // Main program structure // - Data definitions // - Core functions diff --git a/lessons/nosql/stage-5/level-4/lesson.md b/lessons/nosql/stage-5/level-4/lesson.md index bc25b0c..4dd5f61 100644 --- a/lessons/nosql/stage-5/level-4/lesson.md +++ b/lessons/nosql/stage-5/level-4/lesson.md @@ -233,7 +233,7 @@ Follow these stages: **Your architecture will depend on your chosen project, but should include:** -```nosql +``` // Main program structure // - Data definitions // - Core functions diff --git a/lessons/nosql/stage-5/level-5/lesson.md b/lessons/nosql/stage-5/level-5/lesson.md index d53cd21..da0f4e2 100644 --- a/lessons/nosql/stage-5/level-5/lesson.md +++ b/lessons/nosql/stage-5/level-5/lesson.md @@ -238,7 +238,7 @@ Follow these stages: **Your architecture will depend on your chosen project, but should include:** -```nosql +``` // Main program structure // - Data definitions // - Core functions diff --git a/lessons/nosql/stage-5/level-6/lesson.md b/lessons/nosql/stage-5/level-6/lesson.md index cd0f960..b84134f 100644 --- a/lessons/nosql/stage-5/level-6/lesson.md +++ b/lessons/nosql/stage-5/level-6/lesson.md @@ -232,7 +232,7 @@ Follow these stages: **Your architecture will depend on your chosen project, but should include:** -```nosql +``` // Main program structure // - Data definitions // - Core functions diff --git a/lessons/nosql/stage-5/level-7/lesson.md b/lessons/nosql/stage-5/level-7/lesson.md index 4572baa..e7e5d86 100644 --- a/lessons/nosql/stage-5/level-7/lesson.md +++ b/lessons/nosql/stage-5/level-7/lesson.md @@ -235,7 +235,7 @@ Follow these stages: **Your architecture will depend on your chosen project, but should include:** -```nosql +``` // Main program structure // - Data definitions // - Core functions diff --git a/lessons/php/stage-1/level-1/lesson.md b/lessons/php/stage-1/level-1/lesson.md index 8cad173..000ce6e 100644 --- a/lessons/php/stage-1/level-1/lesson.md +++ b/lessons/php/stage-1/level-1/lesson.md @@ -23,7 +23,7 @@ Welcome to your first PHP program! Today, you'll create and run your very first **Copy the following code EXACTLY as shown below into `main.php`** -```php +``` @@ -34,12 +34,12 @@ echo "Hello, World!\n"; ### How to Run **Method 1 (Vim - Recommended):** -```php +``` r ``` **Method 2 (Terminal):** -```bash +``` php main.php ``` @@ -93,44 +93,26 @@ You just created a real PHP program! Here's what makes it work: --- -## ANSWER KEY (No peeking until you've tried!) - -### Code Breakdown - -The code you copied demonstrates fundamental PHP concepts: - -**Key Components:** -- Syntax rules specific to PHP -- How data is stored and manipulated -- Input/output operations -- Program flow and structure +## ANSWER KEY (No cheating until you've tried!) -### Common Errors & Solutions +### Solution -| Error | Cause | Solution | -|-------|-------|----------| -| Syntax error | Typo in code | Double-check spelling and punctuation | -| Runtime error | Code runs but crashes | Check your logic and data types | -| Unexpected output | Logic error | Review your algorithm step-by-step | +``` + +``` -### Bonus Knowledge +### Explanation -- PHP has a rich ecosystem of libraries and tools -- Understanding these basics prepares you for advanced topics -- Practice is key - try writing similar programs from scratch -- Every expert programmer started exactly where you are now! +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -### Real-World Applications +### Success Criteria -This concept is used in: -1. Professional software development -2. Web applications and mobile apps -3. Data analysis and scientific computing -4. Automation and scripting -5. Game development +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -**Excellent work! You've mastered a fundamental concept!** - -*Ready for the next challenge? Keep going!* +**Great job! You've completed this lesson!** diff --git a/lessons/php/stage-1/level-2/lesson.md b/lessons/php/stage-1/level-2/lesson.md index 82d2d2b..4341674 100644 --- a/lessons/php/stage-1/level-2/lesson.md +++ b/lessons/php/stage-1/level-2/lesson.md @@ -23,7 +23,7 @@ Learn how to store and work with different types of data in PHP. **Copy the following code EXACTLY as shown below into `main.php`** -```php +``` r ``` **Method 2 (Terminal):** -```bash +``` php main.php ``` @@ -109,44 +109,40 @@ You just created a real PHP program! Here's what makes it work: --- -## ANSWER KEY (No peeking until you've tried!) +## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -The code you copied demonstrates fundamental PHP concepts: +``` + +``` -### Bonus Knowledge +### Explanation -- PHP has a rich ecosystem of libraries and tools -- Understanding these basics prepares you for advanced topics -- Practice is key - try writing similar programs from scratch -- Every expert programmer started exactly where you are now! +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -### Real-World Applications +### Success Criteria -This concept is used in: -1. Professional software development -2. Web applications and mobile apps -3. Data analysis and scientific computing -4. Automation and scripting -5. Game development +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -**Excellent work! You've mastered a fundamental concept!** - -*Ready for the next challenge? Keep going!* +**Great job! You've completed this lesson!** diff --git a/lessons/php/stage-1/level-3/lesson.md b/lessons/php/stage-1/level-3/lesson.md index 6df3c63..40c5268 100644 --- a/lessons/php/stage-1/level-3/lesson.md +++ b/lessons/php/stage-1/level-3/lesson.md @@ -23,7 +23,7 @@ Master arithmetic operations and use PHP as your powerful calculator. **Copy the following code EXACTLY as shown below into `main.php`** -```php +``` r ``` **Method 2 (Terminal):** -```bash +``` php main.php ``` @@ -104,44 +104,34 @@ You just created a real PHP program! Here's what makes it work: --- -## ANSWER KEY (No peeking until you've tried!) - -### Code Breakdown - -The code you copied demonstrates fundamental PHP concepts: +## ANSWER KEY (No cheating until you've tried!) -**Key Components:** -- Syntax rules specific to PHP -- How data is stored and manipulated -- Input/output operations -- Program flow and structure +### Solution -### Common Errors & Solutions +``` + +``` -### Bonus Knowledge +### Explanation -- PHP has a rich ecosystem of libraries and tools -- Understanding these basics prepares you for advanced topics -- Practice is key - try writing similar programs from scratch -- Every expert programmer started exactly where you are now! +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -### Real-World Applications +### Success Criteria -This concept is used in: -1. Professional software development -2. Web applications and mobile apps -3. Data analysis and scientific computing -4. Automation and scripting -5. Game development +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -**Excellent work! You've mastered a fundamental concept!** - -*Ready for the next challenge? Keep going!* +**Great job! You've completed this lesson!** diff --git a/lessons/php/stage-1/level-4/lesson.md b/lessons/php/stage-1/level-4/lesson.md index 5c3c34f..7ab9daf 100644 --- a/lessons/php/stage-1/level-4/lesson.md +++ b/lessons/php/stage-1/level-4/lesson.md @@ -23,7 +23,7 @@ Make your programs interactive by reading input from users. **Copy the following code EXACTLY as shown below into `main.php`** -```php +``` r ``` **Method 2 (Terminal):** -```bash +``` php main.php ``` @@ -100,44 +100,33 @@ You just created a real PHP program! Here's what makes it work: --- -## ANSWER KEY (No peeking until you've tried!) - -### Code Breakdown +## ANSWER KEY (No cheating until you've tried!) -The code you copied demonstrates fundamental PHP concepts: +### Solution -**Key Components:** -- Syntax rules specific to PHP -- How data is stored and manipulated -- Input/output operations -- Program flow and structure +``` + +``` -### Bonus Knowledge +### Explanation -- PHP has a rich ecosystem of libraries and tools -- Understanding these basics prepares you for advanced topics -- Practice is key - try writing similar programs from scratch -- Every expert programmer started exactly where you are now! +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -### Real-World Applications +### Success Criteria -This concept is used in: -1. Professional software development -2. Web applications and mobile apps -3. Data analysis and scientific computing -4. Automation and scripting -5. Game development +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -**Excellent work! You've mastered a fundamental concept!** - -*Ready for the next challenge? Keep going!* +**Great job! You've completed this lesson!** diff --git a/lessons/php/stage-1/level-5/lesson.md b/lessons/php/stage-1/level-5/lesson.md index 3d50826..6b68803 100644 --- a/lessons/php/stage-1/level-5/lesson.md +++ b/lessons/php/stage-1/level-5/lesson.md @@ -23,7 +23,7 @@ Add decision-making to your programs with if/else statements. **Copy the following code EXACTLY as shown below into `main.php`** -```php +``` = 90) { ### How to Run **Method 1 (Vim - Recommended):** -```php +``` r ``` **Method 2 (Terminal):** -```bash +``` php main.php ``` @@ -106,44 +106,39 @@ You just created a real PHP program! Here's what makes it work: --- -## ANSWER KEY (No peeking until you've tried!) +## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -The code you copied demonstrates fundamental PHP concepts: - -**Key Components:** -- Syntax rules specific to PHP -- How data is stored and manipulated -- Input/output operations -- Program flow and structure - -### Common Errors & Solutions +``` += 90) { + echo "Grade: A - Excellent!\n"; +} elseif ($score >= 80) { + echo "Grade: B - Good job!\n"; +} elseif ($score >= 70) { + echo "Grade: C - Passing\n"; +} elseif ($score >= 60) { + echo "Grade: D - Needs improvement\n"; +} else { + echo "Grade: F - Study harder!\n"; +} +?> +``` -### Bonus Knowledge +### Explanation -- PHP has a rich ecosystem of libraries and tools -- Understanding these basics prepares you for advanced topics -- Practice is key - try writing similar programs from scratch -- Every expert programmer started exactly where you are now! +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -### Real-World Applications +### Success Criteria -This concept is used in: -1. Professional software development -2. Web applications and mobile apps -3. Data analysis and scientific computing -4. Automation and scripting -5. Game development +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -**Excellent work! You've mastered a fundamental concept!** - -*Ready for the next challenge? Keep going!* +**Great job! You've completed this lesson!** diff --git a/lessons/php/stage-1/level-6/lesson.md b/lessons/php/stage-1/level-6/lesson.md index 69f2cc6..36808ea 100644 --- a/lessons/php/stage-1/level-6/lesson.md +++ b/lessons/php/stage-1/level-6/lesson.md @@ -23,7 +23,7 @@ Learn to repeat actions efficiently using loops. **Copy the following code EXACTLY as shown below into `main.php`** -```php +``` r ``` **Method 2 (Terminal):** -```bash +``` php main.php ``` @@ -114,44 +114,47 @@ You just created a real PHP program! Here's what makes it work: --- -## ANSWER KEY (No peeking until you've tried!) - -### Code Breakdown +## ANSWER KEY (No cheating until you've tried!) -The code you copied demonstrates fundamental PHP concepts: +### Solution -**Key Components:** -- Syntax rules specific to PHP -- How data is stored and manipulated -- Input/output operations -- Program flow and structure +``` + 0) { + echo "$count\n"; + $count--; +} +echo "Blastoff!\n"; -| Error | Cause | Solution | -|-------|-------|----------| -| Syntax error | Typo in code | Double-check spelling and punctuation | -| Runtime error | Code runs but crashes | Check your logic and data types | -| Unexpected output | Logic error | Review your algorithm step-by-step | +// Multiplication table +$num = 7; +echo "\n$num times table:\n"; +for ($i = 1; $i <= 10; $i++) { + echo "$num × $i = " . ($num * $i) . "\n"; +} +?> +``` -### Bonus Knowledge +### Explanation -- PHP has a rich ecosystem of libraries and tools -- Understanding these basics prepares you for advanced topics -- Practice is key - try writing similar programs from scratch -- Every expert programmer started exactly where you are now! +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -### Real-World Applications +### Success Criteria -This concept is used in: -1. Professional software development -2. Web applications and mobile apps -3. Data analysis and scientific computing -4. Automation and scripting -5. Game development +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -**Excellent work! You've mastered a fundamental concept!** - -*Ready for the next challenge? Keep going!* +**Great job! You've completed this lesson!** diff --git a/lessons/php/stage-1/level-7/lesson.md b/lessons/php/stage-1/level-7/lesson.md index 9a0475c..632a45b 100644 --- a/lessons/php/stage-1/level-7/lesson.md +++ b/lessons/php/stage-1/level-7/lesson.md @@ -23,7 +23,7 @@ Organize your code into reusable functions/methods. **Copy the following code EXACTLY as shown below into `main.php`** -```php +``` r ``` **Method 2 (Terminal):** -```bash +``` php main.php ``` @@ -118,44 +118,51 @@ You just created a real PHP program! Here's what makes it work: --- -## ANSWER KEY (No peeking until you've tried!) +## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -The code you copied demonstrates fundamental PHP concepts: +``` + +``` -### Real-World Applications +### Explanation -This concept is used in: -1. Professional software development -2. Web applications and mobile apps -3. Data analysis and scientific computing -4. Automation and scripting -5. Game development +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. ---- +### Success Criteria + +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does -**Excellent work! You've mastered a fundamental concept!** +--- -*Ready for the next challenge? Keep going!* +**Great job! You've completed this lesson!** diff --git a/lessons/php/stage-2/level-1/lesson.md b/lessons/php/stage-2/level-1/lesson.md index 934400d..094df56 100644 --- a/lessons/php/stage-2/level-1/lesson.md +++ b/lessons/php/stage-2/level-1/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in PHP:** -```php +``` ALGORITHM: Basic Algorithm Translation BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` php hello.php ``` @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in PHP: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```php +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/php/stage-2/level-2/lesson.md b/lessons/php/stage-2/level-2/lesson.md index f51c895..197a601 100644 --- a/lessons/php/stage-2/level-2/lesson.md +++ b/lessons/php/stage-2/level-2/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in PHP:** -```php +``` ALGORITHM: Variables in Algorithms BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` php hello.php ``` @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in PHP: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```php +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/php/stage-2/level-3/lesson.md b/lessons/php/stage-2/level-3/lesson.md index bb38f80..a1bbab8 100644 --- a/lessons/php/stage-2/level-3/lesson.md +++ b/lessons/php/stage-2/level-3/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in PHP:** -```php +``` ALGORITHM: Mathematical Algorithms BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` php hello.php ``` @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in PHP: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```php +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/php/stage-2/level-4/lesson.md b/lessons/php/stage-2/level-4/lesson.md index 74d6e56..7f6ed88 100644 --- a/lessons/php/stage-2/level-4/lesson.md +++ b/lessons/php/stage-2/level-4/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in PHP:** -```php +``` ALGORITHM: Input/Output Algorithms BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` php hello.php ``` @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in PHP: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```php +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/php/stage-2/level-5/lesson.md b/lessons/php/stage-2/level-5/lesson.md index b3a856b..fcbe63a 100644 --- a/lessons/php/stage-2/level-5/lesson.md +++ b/lessons/php/stage-2/level-5/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in PHP:** -```php +``` ALGORITHM: Decision Algorithms BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` php hello.php ``` @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in PHP: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```php +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/php/stage-2/level-6/lesson.md b/lessons/php/stage-2/level-6/lesson.md index 3a61a87..6cae174 100644 --- a/lessons/php/stage-2/level-6/lesson.md +++ b/lessons/php/stage-2/level-6/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in PHP:** -```php +``` ALGORITHM: Loop Algorithms BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` php hello.php ``` @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in PHP: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```php +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/php/stage-2/level-7/lesson.md b/lessons/php/stage-2/level-7/lesson.md index 667a019..f9f64e4 100644 --- a/lessons/php/stage-2/level-7/lesson.md +++ b/lessons/php/stage-2/level-7/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in PHP:** -```php +``` ALGORITHM: Function Design BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` php hello.php ``` @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in PHP: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```php +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/php/stage-3/level-1/lesson.md b/lessons/php/stage-3/level-1/lesson.md index e7c0ea1..8f2c682 100644 --- a/lessons/php/stage-3/level-1/lesson.md +++ b/lessons/php/stage-3/level-1/lesson.md @@ -51,7 +51,7 @@ Simple Problem Analysis - Design an algorithm to solve this problem, then implem ### How to Run 1. **Run the code**: - ```bash + ``` php hello.php ``` @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```php +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/php/stage-3/level-2/lesson.md b/lessons/php/stage-3/level-2/lesson.md index 40220a4..bb3a081 100644 --- a/lessons/php/stage-3/level-2/lesson.md +++ b/lessons/php/stage-3/level-2/lesson.md @@ -51,7 +51,7 @@ Data Structure Planning - Design an algorithm to solve this problem, then implem ### How to Run 1. **Run the code**: - ```bash + ``` php hello.php ``` @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```php +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/php/stage-3/level-3/lesson.md b/lessons/php/stage-3/level-3/lesson.md index f718f86..ad83bcc 100644 --- a/lessons/php/stage-3/level-3/lesson.md +++ b/lessons/php/stage-3/level-3/lesson.md @@ -51,7 +51,7 @@ Mathematical Problems - Design an algorithm to solve this problem, then implemen ### How to Run 1. **Run the code**: - ```bash + ``` php hello.php ``` @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```php +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/php/stage-3/level-4/lesson.md b/lessons/php/stage-3/level-4/lesson.md index 09d9b96..61d3dd8 100644 --- a/lessons/php/stage-3/level-4/lesson.md +++ b/lessons/php/stage-3/level-4/lesson.md @@ -51,7 +51,7 @@ Text Processing Problems - Design an algorithm to solve this problem, then imple ### How to Run 1. **Run the code**: - ```bash + ``` php hello.php ``` @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```php +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/php/stage-3/level-5/lesson.md b/lessons/php/stage-3/level-5/lesson.md index 3665b7b..2aae924 100644 --- a/lessons/php/stage-3/level-5/lesson.md +++ b/lessons/php/stage-3/level-5/lesson.md @@ -51,7 +51,7 @@ Logic Problems - Design an algorithm to solve this problem, then implement it. ### How to Run 1. **Run the code**: - ```bash + ``` php hello.php ``` @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```php +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/php/stage-3/level-6/lesson.md b/lessons/php/stage-3/level-6/lesson.md index 57e9e2a..6d6c6d2 100644 --- a/lessons/php/stage-3/level-6/lesson.md +++ b/lessons/php/stage-3/level-6/lesson.md @@ -51,7 +51,7 @@ Search Algorithms - Design an algorithm to solve this problem, then implement it ### How to Run 1. **Run the code**: - ```bash + ``` php hello.php ``` @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```php +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/php/stage-3/level-7/lesson.md b/lessons/php/stage-3/level-7/lesson.md index 74f480a..55965af 100644 --- a/lessons/php/stage-3/level-7/lesson.md +++ b/lessons/php/stage-3/level-7/lesson.md @@ -51,7 +51,7 @@ Sorting Algorithms - Design an algorithm to solve this problem, then implement i ### How to Run 1. **Run the code**: - ```bash + ``` php hello.php ``` @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```php +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/php/stage-4/level-1/lesson.md b/lessons/php/stage-4/level-1/lesson.md index 2349e62..5dabfeb 100644 --- a/lessons/php/stage-4/level-1/lesson.md +++ b/lessons/php/stage-4/level-1/lesson.md @@ -51,7 +51,7 @@ Build a complete Calculator Application application that: ### How to Run 1. **Run the code**: - ```bash + ``` php hello.php ``` @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```php +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/php/stage-4/level-2/lesson.md b/lessons/php/stage-4/level-2/lesson.md index fa5ec6a..ad7e766 100644 --- a/lessons/php/stage-4/level-2/lesson.md +++ b/lessons/php/stage-4/level-2/lesson.md @@ -51,7 +51,7 @@ Build a complete Text Analysis Tool application that: ### How to Run 1. **Run the code**: - ```bash + ``` php hello.php ``` @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```php +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/php/stage-4/level-3/lesson.md b/lessons/php/stage-4/level-3/lesson.md index 4cae6ea..8f700d0 100644 --- a/lessons/php/stage-4/level-3/lesson.md +++ b/lessons/php/stage-4/level-3/lesson.md @@ -51,7 +51,7 @@ Build a complete Data Processing application that: ### How to Run 1. **Run the code**: - ```bash + ``` php hello.php ``` @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```php +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/php/stage-4/level-4/lesson.md b/lessons/php/stage-4/level-4/lesson.md index 557341c..e0c0666 100644 --- a/lessons/php/stage-4/level-4/lesson.md +++ b/lessons/php/stage-4/level-4/lesson.md @@ -51,7 +51,7 @@ Build a complete File Operations application that: ### How to Run 1. **Run the code**: - ```bash + ``` php hello.php ``` @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```php +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/php/stage-4/level-5/lesson.md b/lessons/php/stage-4/level-5/lesson.md index bb233d5..ebebdf6 100644 --- a/lessons/php/stage-4/level-5/lesson.md +++ b/lessons/php/stage-4/level-5/lesson.md @@ -51,7 +51,7 @@ Build a complete API Integration application that: ### How to Run 1. **Run the code**: - ```bash + ``` php hello.php ``` @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```php +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/php/stage-4/level-6/lesson.md b/lessons/php/stage-4/level-6/lesson.md index 2c6cb4f..bfe4994 100644 --- a/lessons/php/stage-4/level-6/lesson.md +++ b/lessons/php/stage-4/level-6/lesson.md @@ -51,7 +51,7 @@ Build a complete Database Operations application that: ### How to Run 1. **Run the code**: - ```bash + ``` php hello.php ``` @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```php +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/php/stage-4/level-7/lesson.md b/lessons/php/stage-4/level-7/lesson.md index 79f3b7e..d4d2709 100644 --- a/lessons/php/stage-4/level-7/lesson.md +++ b/lessons/php/stage-4/level-7/lesson.md @@ -51,7 +51,7 @@ Build a complete Complete Application application that: ### How to Run 1. **Run the code**: - ```bash + ``` php hello.php ``` @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```php +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/php/stage-5/level-1/lesson.md b/lessons/php/stage-5/level-1/lesson.md index 2e36357..f9f6f0e 100644 --- a/lessons/php/stage-5/level-1/lesson.md +++ b/lessons/php/stage-5/level-1/lesson.md @@ -242,7 +242,7 @@ Follow these stages: **Your architecture will depend on your chosen project, but should include:** -```php +``` // Main program structure // - Data definitions // - Core functions diff --git a/lessons/php/stage-5/level-2/lesson.md b/lessons/php/stage-5/level-2/lesson.md index 438cd98..fd748db 100644 --- a/lessons/php/stage-5/level-2/lesson.md +++ b/lessons/php/stage-5/level-2/lesson.md @@ -233,7 +233,7 @@ Follow these stages: **Your architecture will depend on your chosen project, but should include:** -```php +``` // Main program structure // - Data definitions // - Core functions diff --git a/lessons/php/stage-5/level-3/lesson.md b/lessons/php/stage-5/level-3/lesson.md index 274b812..a2e3fa7 100644 --- a/lessons/php/stage-5/level-3/lesson.md +++ b/lessons/php/stage-5/level-3/lesson.md @@ -238,7 +238,7 @@ Follow these stages: **Your architecture will depend on your chosen project, but should include:** -```php +``` // Main program structure // - Data definitions // - Core functions diff --git a/lessons/php/stage-5/level-4/lesson.md b/lessons/php/stage-5/level-4/lesson.md index 2d06a84..a71eca1 100644 --- a/lessons/php/stage-5/level-4/lesson.md +++ b/lessons/php/stage-5/level-4/lesson.md @@ -233,7 +233,7 @@ Follow these stages: **Your architecture will depend on your chosen project, but should include:** -```php +``` // Main program structure // - Data definitions // - Core functions diff --git a/lessons/php/stage-5/level-5/lesson.md b/lessons/php/stage-5/level-5/lesson.md index 3b251b7..7598531 100644 --- a/lessons/php/stage-5/level-5/lesson.md +++ b/lessons/php/stage-5/level-5/lesson.md @@ -238,7 +238,7 @@ Follow these stages: **Your architecture will depend on your chosen project, but should include:** -```php +``` // Main program structure // - Data definitions // - Core functions diff --git a/lessons/php/stage-5/level-6/lesson.md b/lessons/php/stage-5/level-6/lesson.md index c2a7c4c..39a4137 100644 --- a/lessons/php/stage-5/level-6/lesson.md +++ b/lessons/php/stage-5/level-6/lesson.md @@ -232,7 +232,7 @@ Follow these stages: **Your architecture will depend on your chosen project, but should include:** -```php +``` // Main program structure // - Data definitions // - Core functions diff --git a/lessons/php/stage-5/level-7/lesson.md b/lessons/php/stage-5/level-7/lesson.md index f957860..8aa0f17 100644 --- a/lessons/php/stage-5/level-7/lesson.md +++ b/lessons/php/stage-5/level-7/lesson.md @@ -235,7 +235,7 @@ Follow these stages: **Your architecture will depend on your chosen project, but should include:** -```php +``` // Main program structure // - Data definitions // - Core functions diff --git a/lessons/powershell/stage-1/level-1/lesson.md b/lessons/powershell/stage-1/level-1/lesson.md index 4ad9593..2e703c6 100644 --- a/lessons/powershell/stage-1/level-1/lesson.md +++ b/lessons/powershell/stage-1/level-1/lesson.md @@ -21,19 +21,19 @@ Welcome to PowerShell! Today, you'll create your first PowerShell script. PowerS Copy the following code EXACTLY as shown into a new file called `hello.ps1`: -```powershell +``` Write-Host "Hello, World!" ``` ### How to Execute -```powershell +``` powershell -File hello.ps1 ``` Expected output: -```powershell +``` Hello, World! ``` @@ -56,20 +56,22 @@ Hello, World! ## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -> **NEEDS_AUTHOR:** This lesson needs a complete answer key with code breakdown, execution process explanation, common errors table, and bonus knowledge section. Reference c-c++/stage-1/level-1/lesson.md for the gold standard format. +``` +Write-Host "Hello, World!" +``` -### Key Concepts +### Explanation -- Review the code structure specific to Powershell -- Understand the execution flow -- Learn common pitfalls and solutions +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -### Next Steps +### Success Criteria -Practice the code and experiment with variations! +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -**Congratulations! Keep coding!** +**Great job! You've completed this lesson!** diff --git a/lessons/powershell/stage-1/level-2/lesson.md b/lessons/powershell/stage-1/level-2/lesson.md index 2ba1c3c..a713083 100644 --- a/lessons/powershell/stage-1/level-2/lesson.md +++ b/lessons/powershell/stage-1/level-2/lesson.md @@ -34,13 +34,13 @@ Write-Host "Student status: $isStudent" ### How to Execute -```bash +``` powershell variables.ps1 ``` Expected output: -```powershell +``` Hello, Alice! You are 25 years old. Your height is 5.6 feet. @@ -85,21 +85,30 @@ Remember to check the `VIM_CHEATSHEET.md` in the root directory for basic Vim co ## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution + +```ps1 +$name = "Alice" +$age = 25 +$height = 5.6 +$isStudent = $true -> **NEEDS_AUTHOR:** This lesson needs a complete answer key with code breakdown, execution process explanation, common errors table, and bonus knowledge section. Reference c-c++/stage-1/level-1/lesson.md for the gold standard format. +Write-Host "Hello, $name!" +Write-Host "You are $age years old." +Write-Host "Your height is $height feet." +Write-Host "Student status: $isStudent" +``` -### Key Concepts +### Explanation -- Review the code structure specific to Powershell -- Understand the execution flow -- Learn common pitfalls and solutions +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -### Next Steps +### Success Criteria -Practice the code and experiment with variations! +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -**Congratulations! Keep coding!** - +**Great job! You've completed this lesson!** diff --git a/lessons/powershell/stage-1/level-3/lesson.md b/lessons/powershell/stage-1/level-3/lesson.md index 2f7cbff..2fa84cd 100644 --- a/lessons/powershell/stage-1/level-3/lesson.md +++ b/lessons/powershell/stage-1/level-3/lesson.md @@ -23,7 +23,7 @@ Master arithmetic operations and use the language as your calculator. **Copy the following code EXACTLY as shown below into `main.ps1`** -```powershell +``` $a = 15 $b = 4 @@ -58,7 +58,7 @@ Write-Host "Precise Division: $x / $y = $($x / $y)" ### The Complete Code -```powershell +``` $a = 15 $b = 4 diff --git a/lessons/powershell/stage-1/level-4/lesson.md b/lessons/powershell/stage-1/level-4/lesson.md index 1a90290..d6943e6 100644 --- a/lessons/powershell/stage-1/level-4/lesson.md +++ b/lessons/powershell/stage-1/level-4/lesson.md @@ -23,7 +23,7 @@ Make your programs interactive by reading input from users. **Copy the following code EXACTLY as shown below into `main.ps1`** -```powershell +``` $name = Read-Host "Enter your name" $age = [int](Read-Host "Enter your age") @@ -52,7 +52,7 @@ Write-Host "Next year you'll be $($age + 1)." ### The Complete Code -```powershell +``` $name = Read-Host "Enter your name" $age = [int](Read-Host "Enter your age") diff --git a/lessons/powershell/stage-1/level-5/lesson.md b/lessons/powershell/stage-1/level-5/lesson.md index 0d15dd1..e0ce6c7 100644 --- a/lessons/powershell/stage-1/level-5/lesson.md +++ b/lessons/powershell/stage-1/level-5/lesson.md @@ -23,7 +23,7 @@ Add decision-making to your programs with if/else statements. **Copy the following code EXACTLY as shown below into `main.ps1`** -```powershell +``` $num = [int](Read-Host "Enter a number") if ($num -gt 0) { @@ -61,7 +61,7 @@ if ($num % 2 -eq 0) { ### The Complete Code -```powershell +``` $num = [int](Read-Host "Enter a number") if ($num -gt 0) { diff --git a/lessons/powershell/stage-1/level-6/lesson.md b/lessons/powershell/stage-1/level-6/lesson.md index 7d9a27b..3f738bf 100644 --- a/lessons/powershell/stage-1/level-6/lesson.md +++ b/lessons/powershell/stage-1/level-6/lesson.md @@ -23,7 +23,7 @@ Learn to repeat actions efficiently using loops. **Copy the following code EXACTLY as shown below into `main.ps1`** -```powershell +``` Write-Host "Counting 1 to 10:" 1..10 | ForEach-Object { Write-Host $_ -NoNewline; Write-Host " " -NoNewline } Write-Host "" @@ -60,7 +60,7 @@ Write-Host "Liftoff!" ### The Complete Code -```powershell +``` Write-Host "Counting 1 to 10:" 1..10 | ForEach-Object { Write-Host $_ -NoNewline; Write-Host " " -NoNewline } Write-Host "" diff --git a/lessons/powershell/stage-1/level-7/lesson.md b/lessons/powershell/stage-1/level-7/lesson.md index ab53c12..e37097c 100644 --- a/lessons/powershell/stage-1/level-7/lesson.md +++ b/lessons/powershell/stage-1/level-7/lesson.md @@ -23,7 +23,7 @@ Organize your code into reusable functions/methods. **Copy the following code EXACTLY as shown below into `main.ps1`** -```powershell +``` function Greet($name) { Write-Host "Hello, $name!" } @@ -67,7 +67,7 @@ Write-Host "5! = $fact" ### The Complete Code -```powershell +``` function Greet($name) { Write-Host "Hello, $name!" } diff --git a/lessons/powershell/stage-2/level-1/lesson.md b/lessons/powershell/stage-2/level-1/lesson.md index ccc920a..6861455 100644 --- a/lessons/powershell/stage-2/level-1/lesson.md +++ b/lessons/powershell/stage-2/level-1/lesson.md @@ -20,7 +20,7 @@ Now that you know the basics, it's time to think like a programmer! You'll take Here's some pseudocode that describes a simple program: -```powershell +``` START print "Welcome to the program!" print "This is my first real program" @@ -38,14 +38,14 @@ Hints: ### How to Run -```bash +``` cd ~/.local/share/learn/workspaces/powershell/stage-2/level-1 powershell main.ps1 ``` Expected output: -```powershell +``` Welcome to the program! This is my first real program I'm learning to code! @@ -67,36 +67,28 @@ If you're stuck, here's what your code should look like (don't peek until you tr --- -## ANSWER KEY - -```ps1 -``` - -(Fill in based on language-specific syntax) - -```powershell - ---- - -## What's Different About Stage 2? +## ANSWER KEY (No cheating until you've tried!) -**Stage 1 (Copying):** Code was provided, you typed it -**Stage 2 (Pseudocode→Code):** Logic is provided, you write the code +### Solution -This is a crucial step! You're now writing code from specifications, not just copying. This is how real programming works. - -### Key Concepts +``` +START + print "Welcome to the program!" + print "This is my first real program" + print "I'm learning to code!" +END +``` -- Pseudocode is language-independent - the same pseudocode could translate to many languages -- Your job is to understand the logic and implement it correctly -- Different languages have different syntax, but the logic is the same +### Explanation ---- +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -## Need Help with Vim? +### Success Criteria -Remember to check the `VIM_CHEATSHEET.md` in the root directory for basic Vim commands! +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -
+**Great job! You've completed this lesson!** diff --git a/lessons/powershell/stage-2/level-2/lesson.md b/lessons/powershell/stage-2/level-2/lesson.md index 3119b2d..6740102 100644 --- a/lessons/powershell/stage-2/level-2/lesson.md +++ b/lessons/powershell/stage-2/level-2/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Powershell:** -```powershell +``` ALGORITHM: Variables in Algorithms BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` powershell -File hello.ps1 ``` @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in Powershell 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```powershell +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/powershell/stage-2/level-3/lesson.md b/lessons/powershell/stage-2/level-3/lesson.md index 912d146..e181410 100644 --- a/lessons/powershell/stage-2/level-3/lesson.md +++ b/lessons/powershell/stage-2/level-3/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Powershell:** -```powershell +``` ALGORITHM: Mathematical Algorithms BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` powershell -File hello.ps1 ``` @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in Powershell 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```powershell +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/powershell/stage-2/level-4/lesson.md b/lessons/powershell/stage-2/level-4/lesson.md index 9b58c32..3706d78 100644 --- a/lessons/powershell/stage-2/level-4/lesson.md +++ b/lessons/powershell/stage-2/level-4/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Powershell:** -```powershell +``` ALGORITHM: Input/Output Algorithms BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` powershell -File hello.ps1 ``` @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in Powershell 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```powershell +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/powershell/stage-2/level-5/lesson.md b/lessons/powershell/stage-2/level-5/lesson.md index 06e97b9..ca26717 100644 --- a/lessons/powershell/stage-2/level-5/lesson.md +++ b/lessons/powershell/stage-2/level-5/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Powershell:** -```powershell +``` ALGORITHM: Decision Algorithms BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` powershell -File hello.ps1 ``` @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in Powershell 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```powershell +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/powershell/stage-2/level-6/lesson.md b/lessons/powershell/stage-2/level-6/lesson.md index 580de7a..a5bf7ea 100644 --- a/lessons/powershell/stage-2/level-6/lesson.md +++ b/lessons/powershell/stage-2/level-6/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Powershell:** -```powershell +``` ALGORITHM: Loop Algorithms BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` powershell -File hello.ps1 ``` @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in Powershell 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```powershell +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/powershell/stage-2/level-7/lesson.md b/lessons/powershell/stage-2/level-7/lesson.md index 296b99a..48d4e5c 100644 --- a/lessons/powershell/stage-2/level-7/lesson.md +++ b/lessons/powershell/stage-2/level-7/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Powershell:** -```powershell +``` ALGORITHM: Function Design BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` powershell -File hello.ps1 ``` @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in Powershell 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```powershell +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/powershell/stage-3/level-1/lesson.md b/lessons/powershell/stage-3/level-1/lesson.md index 774cdcf..b4d2355 100644 --- a/lessons/powershell/stage-3/level-1/lesson.md +++ b/lessons/powershell/stage-3/level-1/lesson.md @@ -22,7 +22,7 @@ You're now ready for Stage 3! This is where you start thinking like a real progr Step 1: Write the pseudocode first -```powershell +``` What should happen: 1. Print "Hello, [name]" @@ -38,7 +38,7 @@ Create `main.powershell.powershell` with your solution. ### How to Run 1. **Run the code**: - ```bash + ``` powershell -File hello.ps1 ``` @@ -87,21 +87,26 @@ Check the `VIM_CHEATSHEET.md` for basic Vim commands! ## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -> **NEEDS_AUTHOR:** This lesson needs a complete answer key with code breakdown, execution process explanation, common errors table, and bonus knowledge section. Reference c-c++/stage-1/level-1/lesson.md for the gold standard format. +``` +What should happen: +1. Print "Hello, [name]" -### Key Concepts +Write your pseudocode in plain English below: +(Your pseudocode here) +``` -- Review the code structure specific to Powershell -- Understand the execution flow -- Learn common pitfalls and solutions +### Explanation -### Next Steps +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -Practice the code and experiment with variations! +### Success Criteria ---- +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does -**Congratulations! Keep coding!** +--- +**Great job! You've completed this lesson!** diff --git a/lessons/powershell/stage-3/level-2/lesson.md b/lessons/powershell/stage-3/level-2/lesson.md index fc37a20..b8076bf 100644 --- a/lessons/powershell/stage-3/level-2/lesson.md +++ b/lessons/powershell/stage-3/level-2/lesson.md @@ -51,7 +51,7 @@ Data Structure Planning - Design an algorithm to solve this problem, then implem ### How to Run 1. **Run the code**: - ```bash + ``` powershell -File hello.ps1 ``` @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```powershell +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/powershell/stage-3/level-3/lesson.md b/lessons/powershell/stage-3/level-3/lesson.md index 84c7537..8c33b45 100644 --- a/lessons/powershell/stage-3/level-3/lesson.md +++ b/lessons/powershell/stage-3/level-3/lesson.md @@ -51,7 +51,7 @@ Mathematical Problems - Design an algorithm to solve this problem, then implemen ### How to Run 1. **Run the code**: - ```bash + ``` powershell -File hello.ps1 ``` @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```powershell +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/powershell/stage-3/level-4/lesson.md b/lessons/powershell/stage-3/level-4/lesson.md index 003637d..88c0af1 100644 --- a/lessons/powershell/stage-3/level-4/lesson.md +++ b/lessons/powershell/stage-3/level-4/lesson.md @@ -51,7 +51,7 @@ Text Processing Problems - Design an algorithm to solve this problem, then imple ### How to Run 1. **Run the code**: - ```bash + ``` powershell -File hello.ps1 ``` @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```powershell +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/powershell/stage-3/level-5/lesson.md b/lessons/powershell/stage-3/level-5/lesson.md index 7cc65b5..9dd571f 100644 --- a/lessons/powershell/stage-3/level-5/lesson.md +++ b/lessons/powershell/stage-3/level-5/lesson.md @@ -51,7 +51,7 @@ Logic Problems - Design an algorithm to solve this problem, then implement it. ### How to Run 1. **Run the code**: - ```bash + ``` powershell -File hello.ps1 ``` @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```powershell +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/powershell/stage-3/level-6/lesson.md b/lessons/powershell/stage-3/level-6/lesson.md index d3ba929..75210e9 100644 --- a/lessons/powershell/stage-3/level-6/lesson.md +++ b/lessons/powershell/stage-3/level-6/lesson.md @@ -51,7 +51,7 @@ Search Algorithms - Design an algorithm to solve this problem, then implement it ### How to Run 1. **Run the code**: - ```bash + ``` powershell -File hello.ps1 ``` @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```powershell +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/powershell/stage-3/level-7/lesson.md b/lessons/powershell/stage-3/level-7/lesson.md index 45cb09e..9f2d155 100644 --- a/lessons/powershell/stage-3/level-7/lesson.md +++ b/lessons/powershell/stage-3/level-7/lesson.md @@ -51,7 +51,7 @@ Sorting Algorithms - Design an algorithm to solve this problem, then implement i ### How to Run 1. **Run the code**: - ```bash + ``` powershell -File hello.ps1 ``` @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```powershell +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/powershell/stage-4/level-1/lesson.md b/lessons/powershell/stage-4/level-1/lesson.md index 445eb59..50614df 100644 --- a/lessons/powershell/stage-4/level-1/lesson.md +++ b/lessons/powershell/stage-4/level-1/lesson.md @@ -30,7 +30,7 @@ Requirements: ### How to Run 1. **Run the code**: - ```bash + ``` powershell -File hello.ps1 ``` diff --git a/lessons/powershell/stage-4/level-2/lesson.md b/lessons/powershell/stage-4/level-2/lesson.md index 2f88ec9..3cfe43c 100644 --- a/lessons/powershell/stage-4/level-2/lesson.md +++ b/lessons/powershell/stage-4/level-2/lesson.md @@ -51,7 +51,7 @@ Build a complete Text Analysis Tool application that: ### How to Run 1. **Run the code**: - ```bash + ``` powershell -File hello.ps1 ``` @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```powershell +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/powershell/stage-4/level-3/lesson.md b/lessons/powershell/stage-4/level-3/lesson.md index 77a2556..1dadfa0 100644 --- a/lessons/powershell/stage-4/level-3/lesson.md +++ b/lessons/powershell/stage-4/level-3/lesson.md @@ -51,7 +51,7 @@ Build a complete Data Processing application that: ### How to Run 1. **Run the code**: - ```bash + ``` powershell -File hello.ps1 ``` @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```powershell +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/powershell/stage-4/level-4/lesson.md b/lessons/powershell/stage-4/level-4/lesson.md index e9370cd..47f887f 100644 --- a/lessons/powershell/stage-4/level-4/lesson.md +++ b/lessons/powershell/stage-4/level-4/lesson.md @@ -51,7 +51,7 @@ Build a complete File Operations application that: ### How to Run 1. **Run the code**: - ```bash + ``` powershell -File hello.ps1 ``` @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```powershell +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/powershell/stage-4/level-5/lesson.md b/lessons/powershell/stage-4/level-5/lesson.md index 881b2de..459b938 100644 --- a/lessons/powershell/stage-4/level-5/lesson.md +++ b/lessons/powershell/stage-4/level-5/lesson.md @@ -51,7 +51,7 @@ Build a complete API Integration application that: ### How to Run 1. **Run the code**: - ```bash + ``` powershell -File hello.ps1 ``` @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```powershell +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/powershell/stage-4/level-6/lesson.md b/lessons/powershell/stage-4/level-6/lesson.md index aa3546f..50bf65c 100644 --- a/lessons/powershell/stage-4/level-6/lesson.md +++ b/lessons/powershell/stage-4/level-6/lesson.md @@ -51,7 +51,7 @@ Build a complete Database Operations application that: ### How to Run 1. **Run the code**: - ```bash + ``` powershell -File hello.ps1 ``` @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```powershell +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/powershell/stage-4/level-7/lesson.md b/lessons/powershell/stage-4/level-7/lesson.md index 77a27ff..1b756e8 100644 --- a/lessons/powershell/stage-4/level-7/lesson.md +++ b/lessons/powershell/stage-4/level-7/lesson.md @@ -51,7 +51,7 @@ Build a complete Complete Application application that: ### How to Run 1. **Run the code**: - ```bash + ``` powershell -File hello.ps1 ``` @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```powershell +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/powershell/stage-5/level-1/lesson.md b/lessons/powershell/stage-5/level-1/lesson.md index 46c81ce..6ed2418 100644 --- a/lessons/powershell/stage-5/level-1/lesson.md +++ b/lessons/powershell/stage-5/level-1/lesson.md @@ -30,7 +30,7 @@ You're going to build a complete Powershell application. This is a real project ### How to Run 1. **Run the code**: - ```bash + ``` powershell -File hello.ps1 ``` diff --git a/lessons/powershell/stage-5/level-2/lesson.md b/lessons/powershell/stage-5/level-2/lesson.md index d15bfe1..b285b66 100644 --- a/lessons/powershell/stage-5/level-2/lesson.md +++ b/lessons/powershell/stage-5/level-2/lesson.md @@ -58,7 +58,7 @@ Create a production-ready CLI Tool using Powershell with: ### How to Run 1. **Run the code**: - ```bash + ``` powershell -File hello.ps1 ``` diff --git a/lessons/powershell/stage-5/level-3/lesson.md b/lessons/powershell/stage-5/level-3/lesson.md index b9eb979..029e0db 100644 --- a/lessons/powershell/stage-5/level-3/lesson.md +++ b/lessons/powershell/stage-5/level-3/lesson.md @@ -58,7 +58,7 @@ Create a production-ready REST API using Powershell with: ### How to Run 1. **Run the code**: - ```bash + ``` powershell -File hello.ps1 ``` diff --git a/lessons/powershell/stage-5/level-4/lesson.md b/lessons/powershell/stage-5/level-4/lesson.md index 92dc0f1..dc4dd8b 100644 --- a/lessons/powershell/stage-5/level-4/lesson.md +++ b/lessons/powershell/stage-5/level-4/lesson.md @@ -58,7 +58,7 @@ Create a production-ready Data Visualization using Powershell with: ### How to Run 1. **Run the code**: - ```bash + ``` powershell -File hello.ps1 ``` diff --git a/lessons/powershell/stage-5/level-5/lesson.md b/lessons/powershell/stage-5/level-5/lesson.md index 8a680a3..9690cac 100644 --- a/lessons/powershell/stage-5/level-5/lesson.md +++ b/lessons/powershell/stage-5/level-5/lesson.md @@ -58,7 +58,7 @@ Create a production-ready Automated Testing using Powershell with: ### How to Run 1. **Run the code**: - ```bash + ``` powershell -File hello.ps1 ``` diff --git a/lessons/powershell/stage-5/level-6/lesson.md b/lessons/powershell/stage-5/level-6/lesson.md index e2d540e..5a94c78 100644 --- a/lessons/powershell/stage-5/level-6/lesson.md +++ b/lessons/powershell/stage-5/level-6/lesson.md @@ -58,7 +58,7 @@ Create a production-ready Performance Optimization using Powershell with: ### How to Run 1. **Run the code**: - ```bash + ``` powershell -File hello.ps1 ``` diff --git a/lessons/powershell/stage-5/level-7/lesson.md b/lessons/powershell/stage-5/level-7/lesson.md index 8a249aa..7ecab9f 100644 --- a/lessons/powershell/stage-5/level-7/lesson.md +++ b/lessons/powershell/stage-5/level-7/lesson.md @@ -58,7 +58,7 @@ Create a production-ready Final Capstone Project using Powershell with: ### How to Run 1. **Run the code**: - ```bash + ``` powershell -File hello.ps1 ``` diff --git a/lessons/python/stage-1/level-1/lesson.md b/lessons/python/stage-1/level-1/lesson.md index c8eee0b..698acaf 100644 --- a/lessons/python/stage-1/level-1/lesson.md +++ b/lessons/python/stage-1/level-1/lesson.md @@ -24,9 +24,9 @@ Welcome to your first step into programming with Python! Today, you'll learn how **Copy the following code EXACTLY as shown below into a new file called `hello.py`** -```python +``` print("Hello, World!") -```python +``` --- @@ -34,18 +34,18 @@ print("Hello, World!") 1. **Open your terminal** (or command prompt) 2. **Navigate to where you saved your file**: - ```bash + ``` cd /path/to/your/folder - ```python + ``` 3. **Run the code**: - ```bash + ``` python3 hello.py - ```bash + ``` **Expected output:** -```python +``` Hello, World! -```python +``` --- @@ -92,9 +92,9 @@ Remember to check the `VIM_CHEATSHEET.md` in the root directory for basic Vim co ### Code Breakdown -```python +``` print("Hello, World!") -```python +``` - **`print`** = Built-in function that displays text - **`"`** = String literal start/end delimiters @@ -126,7 +126,7 @@ print("Hello, World!") --- - **Congratulations! You've written your first Python program!** + **Congratulations! You've written your first Python program!** *Keep moving forward - next up: Variables!* @@ -146,40 +146,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```py -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard python conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/python/stage-1/level-2/lesson.md b/lessons/python/stage-1/level-2/lesson.md index b149c2c..5fcc70b 100644 --- a/lessons/python/stage-1/level-2/lesson.md +++ b/lessons/python/stage-1/level-2/lesson.md @@ -24,7 +24,7 @@ Now that you know how to run Python programs, let's learn about variables! Varia **Copy the following code EXACTLY as shown below into a new file called `variables.py`** -```python +``` # Store some information in variables name = "Alice" age = 25 @@ -36,7 +36,7 @@ print(f"Hello, {name}!") print(f"You are {age} years old.") print(f"Your height is {height} feet.") print(f"Student status: {is_student}") -```python +``` --- @@ -44,21 +44,21 @@ print(f"Student status: {is_student}") 1. **Open your terminal** (or command prompt) 2. **Navigate to where you saved your file**: - ```bash + ``` cd /path/to/your/folder - ```python + ``` 3. **Run the code**: - ```bash + ``` python3 variables.py - ```bash + ``` **Expected output:** -```python +``` Hello, Alice! You are 25 years old. Your height is 5.6 feet. Student status: True -```python +``` --- @@ -107,13 +107,13 @@ Remember to check the `VIM_CHEATSHEET.md` in the root directory for basic Vim co ### Code Breakdown -```python +``` # Store some information in variables name = "Alice" age = 25 height = 5.6 is_student = True -```python +``` - **`name = "Alice"`** = Creates variable `name` and assigns string value - **`age = 25`** = Creates variable `age` and assigns integer value @@ -121,13 +121,13 @@ is_student = True - **`is_student = True`** = Creates variable `is_student` and assigns boolean value - **`#`** = Comment - ignored by Python, for human readers -```python +``` # Display the information print(f"Hello, {name}!") print(f"You are {age} years old.") print(f"Your height is {height} feet.") print(f"Student status: {is_student}") -```python +``` - **`f"Hello, {name}!"`** = F-string formatting - inserts variable values into strings - **`{name}`** = Placeholder where variable value gets inserted @@ -159,7 +159,7 @@ print(f"Student status: {is_student}") --- - **Great job! You now understand variables in Python!** + **Great job! You now understand variables in Python!** *Keep moving forward - next up: Basic Math Operations!* @@ -179,40 +179,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```py -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard python conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/python/stage-1/level-3/lesson.md b/lessons/python/stage-1/level-3/lesson.md index d777af1..5649589 100644 --- a/lessons/python/stage-1/level-3/lesson.md +++ b/lessons/python/stage-1/level-3/lesson.md @@ -24,7 +24,7 @@ Time to do some math with Python! Programming is great for calculations. Python **Copy the following code EXACTLY as shown below into a new file called `math.py`** -```python +``` # Some numbers to work with a = 10 b = 3 @@ -37,7 +37,7 @@ print(f"Division: {a} / {b} = {a / b}") print(f"Integer Division: {a} // {b} = {a // b}") print(f"Modulus (Remainder): {a} % {b} = {a % b}") print(f"Exponentiation: {a} ** {b} = {a ** b}") -```python +``` --- @@ -45,16 +45,16 @@ print(f"Exponentiation: {a} ** {b} = {a ** b}") 1. **Open your terminal** (or command prompt) 2. **Navigate to where you saved your file**: - ```bash + ``` cd /path/to/your/folder - ```python + ``` 3. **Run the code**: - ```bash + ``` python3 math.py - ```bash + ``` **Expected output:** -```python +``` Addition: 10 + 3 = 13 Subtraction: 10 - 3 = 7 Multiplication: 10 * 3 = 30 @@ -62,7 +62,7 @@ Division: 10 / 3 = 3.3333333333333335 Integer Division: 10 // 3 = 3 Modulus (Remainder): 10 % 3 = 1 Exponentiation: 10 ** 3 = 1000 -```python +``` --- @@ -113,16 +113,16 @@ Remember to check the `VIM_CHEATSHEET.md` in the root directory for basic Vim co ### Code Breakdown -```python +``` # Some numbers to work with a = 10 b = 3 -```python +``` - **`a = 10`** = Store 10 in variable `a` - **`b = 3`** = Store 3 in variable `b` -```python +``` # Basic arithmetic operations print(f"Addition: {a} + {b} = {a + b}") print(f"Subtraction: {a} - {b} = {a - b}") @@ -131,7 +131,7 @@ print(f"Division: {a} / {b} = {a / b}") print(f"Integer Division: {a} // {b} = {a // b}") print(f"Modulus (Remainder): {a} % {b} = {a % b}") print(f"Exponentiation: {a} ** {b} = {a ** b}") -```python +``` - **Each line** = Calculates and displays one operation - **`{a + b}`** = Performs calculation and inserts result @@ -174,7 +174,7 @@ Use parentheses `()` to change order: `(2 + 3) * 4 = 20` --- - **Excellent! You can now do math with Python!** + **Excellent! You can now do math with Python!** *Keep moving forward - next up: User Input!* @@ -194,40 +194,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```py -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard python conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/python/stage-1/level-4/lesson.md b/lessons/python/stage-1/level-4/lesson.md index c8b2e33..d7dcb0e 100644 --- a/lessons/python/stage-1/level-4/lesson.md +++ b/lessons/python/stage-1/level-4/lesson.md @@ -24,7 +24,7 @@ So far, our programs have used fixed values. Now let's make programs that intera **Copy the following code EXACTLY as shown below into a new file called `input.py`** -```python +``` # Get user information name = input("What is your name? ") age = int(input("How old are you? ")) @@ -35,7 +35,7 @@ print(f"\nHello, {name}!") print(f"You are {age} years old.") print(f"Your favorite color is {favorite_color}.") print(f"Nice to meet you, {name}!") -```python +``` --- @@ -43,17 +43,17 @@ print(f"Nice to meet you, {name}!") 1. **Open your terminal** (or command prompt) 2. **Navigate to where you saved your file**: - ```bash + ``` cd /path/to/your/folder - ```python + ``` 3. **Run the code**: - ```bash + ``` python3 input.py - ```python + ``` 4. **Follow the prompts** - type your answers when asked! **Example interaction:** -```python +``` What is your name? Alice How old are you? 25 What is your favorite color? Blue @@ -62,7 +62,7 @@ Hello, Alice! You are 25 years old. Your favorite color is Blue. Nice to meet you, Alice! -```python +``` --- @@ -110,24 +110,24 @@ Remember to check the `VIM_CHEATSHEET.md` in the root directory for basic Vim co ### Code Breakdown -```python +``` # Get user information name = input("What is your name? ") age = int(input("How old are you? ")) favorite_color = input("What is your favorite color? ") -```python +``` - **`input("What is your name? ")`** = Displays prompt, gets text input - **`int(input("How old are you? "))`** = Gets input, converts to integer - **`name = ...`** = Stores input in variable `name` -```python +``` # Display personalized message print(f"\nHello, {name}!") print(f"You are {age} years old.") print(f"Your favorite color is {favorite_color}.") print(f"Nice to meet you, {name}!") -```python +``` - **`f"\nHello, {name}!"`** = Newline then personalized greeting - **Uses stored variables** = Program remembers what user typed @@ -163,7 +163,7 @@ print(f"Nice to meet you, {name}!") --- - **Fantastic! Your programs can now talk to users!** + **Fantastic! Your programs can now talk to users!** *Keep moving forward - next up: Conditionals and Decision Making!* @@ -183,40 +183,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```py -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard python conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/python/stage-1/level-5/lesson.md b/lessons/python/stage-1/level-5/lesson.md index 0b6c2fc..c95883c 100644 --- a/lessons/python/stage-1/level-5/lesson.md +++ b/lessons/python/stage-1/level-5/lesson.md @@ -24,7 +24,7 @@ Programs that can make decisions are much more powerful! Python's `if`, `elif`, **Copy the following code EXACTLY as shown below into a new file called `conditionals.py`** -```python +``` # Get user input age = int(input("How old are you? ")) temperature = float(input("What is the temperature in Celsius? ")) @@ -48,7 +48,7 @@ elif temperature < 25: print("It's mild weather.") else: print("It's hot! Stay cool.") -```python +``` --- @@ -56,23 +56,23 @@ else: 1. **Open your terminal** (or command prompt) 2. **Navigate to where you saved your file**: - ```bash + ``` cd /path/to/your/folder - ```python + ``` 3. **Run the code**: - ```bash + ``` python3 conditionals.py - ```python + ``` 4. **Provide input** when prompted! **Example interaction:** -```python +``` How old are you? 25 What is the temperature in Celsius? 22 You are an adult. It's mild weather. -```python +``` --- @@ -120,15 +120,15 @@ Remember to check the `VIM_CHEATSHEET.md` in the root directory for basic Vim co ### Code Breakdown -```python +``` # Get user input age = int(input("How old are you? ")) temperature = float(input("What is the temperature in Celsius? ")) -```python +``` - **Gets numeric input** = Age as integer, temperature as float -```python +``` # Age-based decisions if age < 13: print("You are a child.") @@ -138,7 +138,7 @@ elif age < 65: print("You are an adult.") else: print("You are a senior citizen.") -```python +``` - **`if age < 13:`** = Checks if age is less than 13 - **`elif age < 20:`** = If not child, checks if less than 20 @@ -180,7 +180,7 @@ else: --- - **Awesome! Your programs can now make decisions!** + **Awesome! Your programs can now make decisions!** *Keep moving forward - next up: Loops and Repetition!* @@ -200,40 +200,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```py -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard python conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/python/stage-1/level-6/lesson.md b/lessons/python/stage-1/level-6/lesson.md index d641304..9da9bfe 100644 --- a/lessons/python/stage-1/level-6/lesson.md +++ b/lessons/python/stage-1/level-6/lesson.md @@ -24,7 +24,7 @@ Loops let your program do the same thing multiple times automatically! This is p **Copy the following code EXACTLY as shown below into a new file called `loops.py`** -```python +``` # While loop example - countdown print("While loop countdown:") count = 5 @@ -53,7 +53,7 @@ for i in range(1, 4): result = i * j print(f"{i} × {j} = {result}") print() # Empty line between rows -```python +``` --- @@ -61,16 +61,16 @@ for i in range(1, 4): 1. **Open your terminal** (or command prompt) 2. **Navigate to where you saved your file**: - ```bash + ``` cd /path/to/your/folder - ```python + ``` 3. **Run the code**: - ```bash + ``` python3 loops.py - ```bash + ``` **Expected output:** -```python +``` While loop countdown: Count: 5 Count: 4 @@ -104,7 +104,7 @@ Multiplication table (3x): 3 × 1 = 3 3 × 2 = 6 3 × 3 = 9 -```python +``` --- @@ -152,34 +152,34 @@ Remember to check the `VIM_CHEATSHEET.md` in the root directory for basic Vim co ### Code Breakdown -```python +``` # While loop example - countdown count = 5 while count > 0: print(f"Count: {count}") count = count - 1 -```python +``` - **`while count > 0:`** = Loop while count is greater than 0 - **`count = count - 1`** = Decrement counter each iteration - **Must change condition** = Or loop runs forever! -```python +``` # For loop with range - counting up for i in range(1, 6): print(f"Number: {i}") -```python +``` - **`range(1, 6)`** = Numbers 1, 2, 3, 4, 5 (up to but not including 6) - **`for i in ...:`** = `i` takes each value in sequence - **Automatic counting** = No manual counter needed -```python +``` # For loop - iterating through a list fruits = ["apple", "banana", "orange", "grape"] for fruit in fruits: print(f"I like {fruit}s") -```python +``` - **List** = Collection of items in square brackets `[]` - **`for fruit in fruits:`** = `fruit` becomes each item in list @@ -217,7 +217,7 @@ for fruit in fruits: --- - **Excellent! Your programs can now repeat tasks automatically!** + **Excellent! Your programs can now repeat tasks automatically!** *Keep moving forward - next up: Functions - Code Organization!* @@ -237,40 +237,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```py -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard python conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/python/stage-1/level-7/lesson.md b/lessons/python/stage-1/level-7/lesson.md index f31f082..a879a1b 100644 --- a/lessons/python/stage-1/level-7/lesson.md +++ b/lessons/python/stage-1/level-7/lesson.md @@ -24,7 +24,7 @@ Functions let you organize code into reusable blocks! Instead of repeating the s **Copy the following code EXACTLY as shown below into a new file called `functions.py`** -```python +``` # Function definitions def greet(name): """Return a personalized greeting.""" @@ -63,7 +63,7 @@ print() print("Person information:") display_info("Alice", 25, "New York") display_info("Bob", 30, "London") -```python +``` --- @@ -71,16 +71,16 @@ display_info("Bob", 30, "London") 1. **Open your terminal** (or command prompt) 2. **Navigate to where you saved your file**: - ```bash + ``` cd /path/to/your/folder - ```python + ``` 3. **Run the code**: - ```bash + ``` python3 functions.py - ```bash + ``` **Expected output:** -```python +``` Hello, Alice! Hello, Bob! @@ -102,7 +102,7 @@ Name: Bob Age: 30 City: London -------------------- -```python +``` --- @@ -150,43 +150,43 @@ Remember to check the `VIM_CHEATSHEET.md` in the root directory for basic Vim co ### Code Breakdown -```python +``` def greet(name): """Return a personalized greeting.""" return f"Hello, {name}!" -```python +``` - **`def greet(name):`** = Define function named `greet` with parameter `name` - **`"""Return a personalized greeting."""`** = Docstring (documentation) - **`return f"Hello, {name}!"`** = Return formatted greeting string -```python +``` def calculate_area(length, width): """Calculate the area of a rectangle.""" return length * width -```python +``` - **Two parameters** = `length` and `width` - **Returns calculation** = Result of multiplication - **Called as** = `calculate_area(5, 3)` -```python +``` def is_even(number): """Check if a number is even.""" return number % 2 == 0 -```python +``` - **Boolean return** = Returns `True` or `False` - **`number % 2 == 0`** = Even if remainder when divided by 2 is 0 -```python +``` def display_info(name, age, city): """Display formatted information about a person.""" print(f"Name: {name}") print(f"Age: {age}") print(f"City: {city}") print("-" * 20) -```python +``` - **No return value** = Function prints directly (returns `None`) - **Multiple statements** = Can contain many lines of code @@ -229,7 +229,7 @@ def display_info(name, age, city): --- - **Congratulations! You've mastered Python functions!** + **Congratulations! You've mastered Python functions!** *You've completed Stage 1: Copying Code! Time to move to Stage 2: Pseudocode to Code!* @@ -249,40 +249,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```py -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard python conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/python/stage-2/level-1/lesson.md b/lessons/python/stage-2/level-1/lesson.md index 179acbb..15fdba1 100644 --- a/lessons/python/stage-2/level-1/lesson.md +++ b/lessons/python/stage-2/level-1/lesson.md @@ -23,13 +23,13 @@ Now that you know the basics, it's time to think like a programmer! You'll take Here's some pseudocode that describes a simple program: -```python +``` START print "Welcome to the program!" print "This is my first real program" print "I'm learning to code!" END -```python +``` **Your mission**: Translate this pseudocode into Python code. @@ -46,24 +46,24 @@ Hints: 1. **Open your terminal** 2. **Navigate to your workspace folder**: - ```bash + ``` cd ~/.local/share/learn/workspaces/python/stage-2/level-1 - ```bash + ``` 3. **Edit main.py** with your translated code 4. **Run your program**: - ```bash + ``` python3 main.py - ```python + ``` **Expected output:** -```python +``` Welcome to the program! This is my first real program I'm learning to code! -```python +``` --- @@ -114,11 +114,11 @@ Remember to check the `VIM_CHEATSHEET.md` in the root directory for basic Vim co ### Solution -```python +``` print("Welcome to the program!") print("This is my first real program") print("I'm learning to code!") -```python +``` ### Explanation @@ -146,12 +146,12 @@ Each line of pseudocode translates directly: **3. Pseudocode to Code Mapping** -```python +``` Pseudocode: print "message" Code: print("message") ↑ ↑ Syntax to use in real Python -```python +``` ### Common Mistakes & Solutions @@ -192,40 +192,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```py -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard python conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/python/stage-2/level-2/lesson.md b/lessons/python/stage-2/level-2/lesson.md index 54a3a1b..444a9fb 100644 --- a/lessons/python/stage-2/level-2/lesson.md +++ b/lessons/python/stage-2/level-2/lesson.md @@ -32,7 +32,7 @@ START print name print age END -```python +``` **Your mission**: Translate this pseudocode into Python code. @@ -50,23 +50,23 @@ Hints: 1. **Open your terminal** 2. **Navigate to your workspace**: - ```bash + ``` cd ~/.local/share/learn/workspaces/python/stage-2/level-2 - ```bash + ``` 3. **Edit main.py** 4. **Run it**: - ```bash + ``` python3 main.py - ```python + ``` **Expected output:** -```python +``` Alice 25 -```python +``` --- @@ -103,30 +103,30 @@ Remember to check the `VIM_CHEATSHEET.md` in the root directory for basic Vim co ### Solution -```python +``` name = "Alice" age = 25 print(name) print(age) -```python +``` ### Explanation **Line 1 & 2: Variable Assignment** -```python +``` name = "Alice" # Create variable 'name', store "Alice" age = 25 # Create variable 'age', store 25 -```python +``` The `=` operator assigns values to variables. **Line 3 & 4: Using Variables** -```python +``` print(name) # Print value IN variable name print(age) # Print value IN variable age -```python +``` Without quotes, Python looks up the variable and uses its value. @@ -162,14 +162,14 @@ Without quotes, Python looks up the variable and uses its value. ### How Variables Work -```python +``` Step 1: name = "Alice" Memory: [name] → "Alice" Step 2: print(name) Python: Look up "name" → find "Alice" → print it Output: Alice -```python +``` --- @@ -193,40 +193,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```py -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard python conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/python/stage-2/level-3/lesson.md b/lessons/python/stage-2/level-3/lesson.md index 5cb6c4f..40c205d 100644 --- a/lessons/python/stage-2/level-3/lesson.md +++ b/lessons/python/stage-2/level-3/lesson.md @@ -38,7 +38,7 @@ START print product print quotient END -```python +``` **Your mission**: Translate this into Python code. @@ -48,20 +48,20 @@ END 1. Navigate to workspace: - ```bash + ``` cd ~/.local/share/learn/workspaces/python/stage-2/level-3 - ```bash + ``` 2. Edit and run main.py **Expected output:** -```python +``` 15 5 50 2.0 -```python +``` --- @@ -78,7 +78,7 @@ END ### Solution -```python +``` x = 10 y = 5 sum = x + y @@ -89,7 +89,7 @@ print(sum) print(difference) print(product) print(quotient) -```python +``` ### Key Concepts @@ -102,11 +102,11 @@ print(quotient) **Expression Evaluation:** -```python +``` sum = x + y ↑ ↑ variable values are looked up, added, result stored -```python +``` **Why 2.0 not 2?** In Python 3, division with `/` always returns a float (decimal number). @@ -133,40 +133,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```py -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard python conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/python/stage-2/level-4/lesson.md b/lessons/python/stage-2/level-4/lesson.md index a660116..c0d97a5 100644 --- a/lessons/python/stage-2/level-4/lesson.md +++ b/lessons/python/stage-2/level-4/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Python:** -```python +``` ALGORITHM: Input/Output Algorithms BEGIN @@ -39,7 +39,7 @@ BEGIN // Translate step by step into Python // Test with sample inputs END -```python +``` **Implementation Steps:** 1. Analyze what the algorithm does @@ -54,14 +54,14 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` python3 hello.py - ```python + ``` **Expected output:** -```python +``` Hello, World! -```python +``` ### How to Approach This @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in Python: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```python +``` PSEUDOCODE: READ number IF number > 0 THEN @@ -168,7 +168,7 @@ PSEUDOCODE: ELSE PRINT "Not positive" END IF -```python +``` This becomes structured Python code following the language syntax. @@ -211,40 +211,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```py -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard python conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/python/stage-2/level-5/lesson.md b/lessons/python/stage-2/level-5/lesson.md index 19cab68..a28ba03 100644 --- a/lessons/python/stage-2/level-5/lesson.md +++ b/lessons/python/stage-2/level-5/lesson.md @@ -34,7 +34,7 @@ START else print "You are a minor" END -```python +``` **Translate to Python. Hints:** @@ -49,19 +49,19 @@ END If you enter 20: -```python +``` How old are you? 20 You are an adult -```python +``` If you enter 15: -```python +``` How old are you? 15 You are a minor -```python +``` --- @@ -79,14 +79,14 @@ You are a minor ### Solution -```python +``` print("How old are you?") age = int(input()) if age >= 18: print("You are an adult") else: print("You are a minor") -```python +``` ### Key Concepts @@ -98,12 +98,12 @@ else: **If/Else Structure:** -```python +``` if condition: code if true else: code if false -```python +``` **Indentation:** @@ -132,40 +132,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```py -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard python conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/python/stage-2/level-6/lesson.md b/lessons/python/stage-2/level-6/lesson.md index 5546d6d..cf50dfa 100644 --- a/lessons/python/stage-2/level-6/lesson.md +++ b/lessons/python/stage-2/level-6/lesson.md @@ -30,7 +30,7 @@ START for i = 1 to 5 print i END -```python +``` **Translate to Python. Hints:** @@ -44,13 +44,13 @@ END Expected output: -```python +``` 1 2 3 4 5 -```python +``` --- @@ -68,10 +68,10 @@ Expected output: ### Solution -```python +``` for i in range(1, 6): print(i) -```python +``` ### Key Concepts @@ -95,11 +95,11 @@ for i in range(1, 6): **Why range(1, 6) for "1 to 5"?** -```python +``` range(1, 6) = [1, 2, 3, 4, 5] ↑ ↑ start stop (exclusive) -```python +``` --- @@ -123,40 +123,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```py -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard python conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/python/stage-2/level-7/lesson.md b/lessons/python/stage-2/level-7/lesson.md index 23ffe56..d252ff7 100644 --- a/lessons/python/stage-2/level-7/lesson.md +++ b/lessons/python/stage-2/level-7/lesson.md @@ -34,7 +34,7 @@ START greet("Alice") greet("Bob") END -```python +``` **Translate to Python. Hints:** @@ -49,10 +49,10 @@ END Expected output: -```python +``` Hello, Alice! Hello, Bob! -```python +``` --- @@ -70,23 +70,23 @@ Hello, Bob! ### Solution -```python +``` def greet(name): print("Hello, " + name + "!") greet("Alice") greet("Bob") -```python +``` ### Key Concepts **Defining Functions:** -```python +``` def function_name(parameters): # Code inside function # Indented -```python +``` **Function Components:** @@ -98,10 +98,10 @@ def function_name(parameters): **Calling Functions:** -```python +``` greet("Alice") # Call greet with "Alice" as argument # name = "Alice" inside the function -```python +``` **Parameters vs Arguments:** @@ -138,40 +138,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```py -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard python conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/python/stage-3/level-1/lesson.md b/lessons/python/stage-3/level-1/lesson.md index 3ba184b..980fef5 100644 --- a/lessons/python/stage-3/level-1/lesson.md +++ b/lessons/python/stage-3/level-1/lesson.md @@ -22,9 +22,9 @@ Write a program that: Example: User enters "Alice" and "blue" -```python +``` Hi Alice, I like blue too! -```python +``` --- @@ -70,17 +70,17 @@ START color = get input from user print "Hi " + name + ", I like " + color + " too!" END -```python +``` ### Python Solution -```python +``` print("What is your name?") name = input() print("What is your favorite color?") color = input() print("Hi " + name + ", I like " + color + " too!") -```python +``` ### Explanation @@ -119,40 +119,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```py -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard python conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/python/stage-3/level-2/lesson.md b/lessons/python/stage-3/level-2/lesson.md index 98bed9b..ccef53b 100644 --- a/lessons/python/stage-3/level-2/lesson.md +++ b/lessons/python/stage-3/level-2/lesson.md @@ -51,14 +51,14 @@ Data Structure Planning - Design an algorithm to solve this problem, then implem ### How to Run 1. **Run the code**: - ```bash + ``` python3 hello.py - ```python + ``` **Expected output:** -```python +``` Hello, World! -```python +``` ### How to Approach This @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```python +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -169,7 +169,7 @@ BEGIN - Step 3 4. Display results END -```python +``` Then translate this directly to Python code. @@ -212,40 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```py -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard python conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/python/stage-3/level-3/lesson.md b/lessons/python/stage-3/level-3/lesson.md index e1267dd..42f18ff 100644 --- a/lessons/python/stage-3/level-3/lesson.md +++ b/lessons/python/stage-3/level-3/lesson.md @@ -51,14 +51,14 @@ Mathematical Problems - Design an algorithm to solve this problem, then implemen ### How to Run 1. **Run the code**: - ```bash + ``` python3 hello.py - ```python + ``` **Expected output:** -```python +``` Hello, World! -```python +``` ### How to Approach This @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```python +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -169,7 +169,7 @@ BEGIN - Step 3 4. Display results END -```python +``` Then translate this directly to Python code. @@ -212,40 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```py -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard python conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/python/stage-3/level-4/lesson.md b/lessons/python/stage-3/level-4/lesson.md index 6f1b1dc..07ca8c3 100644 --- a/lessons/python/stage-3/level-4/lesson.md +++ b/lessons/python/stage-3/level-4/lesson.md @@ -51,14 +51,14 @@ Text Processing Problems - Design an algorithm to solve this problem, then imple ### How to Run 1. **Run the code**: - ```bash + ``` python3 hello.py - ```python + ``` **Expected output:** -```python +``` Hello, World! -```python +``` ### How to Approach This @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```python +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -169,7 +169,7 @@ BEGIN - Step 3 4. Display results END -```python +``` Then translate this directly to Python code. @@ -212,40 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```py -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard python conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/python/stage-3/level-5/lesson.md b/lessons/python/stage-3/level-5/lesson.md index cb24d24..531f3c0 100644 --- a/lessons/python/stage-3/level-5/lesson.md +++ b/lessons/python/stage-3/level-5/lesson.md @@ -51,14 +51,14 @@ Logic Problems - Design an algorithm to solve this problem, then implement it. ### How to Run 1. **Run the code**: - ```bash + ``` python3 hello.py - ```python + ``` **Expected output:** -```python +``` Hello, World! -```python +``` ### How to Approach This @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```python +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -169,7 +169,7 @@ BEGIN - Step 3 4. Display results END -```python +``` Then translate this directly to Python code. @@ -212,40 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```py -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard python conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/python/stage-3/level-6/lesson.md b/lessons/python/stage-3/level-6/lesson.md index 37588cb..ed252f9 100644 --- a/lessons/python/stage-3/level-6/lesson.md +++ b/lessons/python/stage-3/level-6/lesson.md @@ -51,14 +51,14 @@ Search Algorithms - Design an algorithm to solve this problem, then implement it ### How to Run 1. **Run the code**: - ```bash + ``` python3 hello.py - ```python + ``` **Expected output:** -```python +``` Hello, World! -```python +``` ### How to Approach This @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```python +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -169,7 +169,7 @@ BEGIN - Step 3 4. Display results END -```python +``` Then translate this directly to Python code. @@ -212,40 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```py -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard python conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/python/stage-3/level-7/lesson.md b/lessons/python/stage-3/level-7/lesson.md index a4dbd20..fa94e5d 100644 --- a/lessons/python/stage-3/level-7/lesson.md +++ b/lessons/python/stage-3/level-7/lesson.md @@ -51,14 +51,14 @@ Sorting Algorithms - Design an algorithm to solve this problem, then implement i ### How to Run 1. **Run the code**: - ```bash + ``` python3 hello.py - ```python + ``` **Expected output:** -```python +``` Hello, World! -```python +``` ### How to Approach This @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```python +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -169,7 +169,7 @@ BEGIN - Step 3 4. Display results END -```python +``` Then translate this directly to Python code. @@ -212,40 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```py -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard python conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/python/stage-4/level-1/lesson.md b/lessons/python/stage-4/level-1/lesson.md index 68f2b9b..d5a56b9 100644 --- a/lessons/python/stage-4/level-1/lesson.md +++ b/lessons/python/stage-4/level-1/lesson.md @@ -37,14 +37,14 @@ The temperature converter should: ### How to Run 1. **Navigate to this level's directory**: - ```bash + ``` cd python/stage-4-full-problem-solving/level-1-simple-application - ```bash + ``` 2. **Run the program**: - ```bash + ``` python3 main.py - ```bash + ``` 3. **Test different conversions** and edge cases @@ -90,18 +90,18 @@ Try these improvements to make the program even better: ### Key Functions -```python +``` def celsius_to_fahrenheit(celsius): """Convert Celsius to Fahrenheit.""" return (celsius * 9/5) + 32 -```python +``` - **Clear naming**: Function name describes exactly what it does - **Documentation**: Docstring explains the purpose - **Simple logic**: One clear mathematical formula - **Return value**: Result is returned for use by caller -```python +``` def get_temperature_input(prompt): """Get temperature input from user with validation.""" while True: @@ -110,7 +110,7 @@ def get_temperature_input(prompt): return temp except ValueError: print(" Invalid input. Please enter a valid number.") -```python +``` - **Input validation**: Uses try/except to handle invalid input - **User-friendly**: Clear error messages @@ -119,7 +119,7 @@ def get_temperature_input(prompt): ### Program Structure -```python +``` main.py ├── Import statements (if needed) ├── Helper functions @@ -129,7 +129,7 @@ main.py │ └── get_menu_choice() └── main() function └── Program logic and menu -```python +``` --- @@ -142,14 +142,14 @@ main.py ### Temperature Conversion Formulas **Celsius to Fahrenheit:** -```python +``` °F = (°C × 9/5) + 32 -```python +``` **Fahrenheit to Celsius:** -```python +``` °C = (°F - 32) × 5/9 -```python +``` ### Key Programming Concepts Demonstrated @@ -195,7 +195,7 @@ main.py --- - **Congratulations! You've built your first complete Python application!** + **Congratulations! You've built your first complete Python application!** *This temperature converter demonstrates the full software development process. Next up: Data Processing Application!* @@ -207,95 +207,3 @@ Understand the key concepts: - Review each function - Understand the flow - Learn the patterns used - - -
- -## Answer Key - -### Complete Solution - -```py -#!/usr/bin/env python3 -""" -Temperature Converter -A simple Python program for converting between Celsius and Fahrenheit. -""" - -def celsius_to_fahrenheit(celsius): - """Convert Celsius to Fahrenheit.""" - return (celsius * 9/5) + 32 - -def fahrenheit_to_celsius(fahrenheit): - """Convert Fahrenheit to Celsius.""" - return (fahrenheit - 32) * 5/9 - -def get_temperature_input(prompt): - """Get temperature input from user with validation.""" - while True: - try: - temp = float(input(prompt)) - return temp - except ValueError: - print("❌ Invalid input. Please enter a valid number.") - -def get_menu_choice(): - """Get menu choice from user with validation.""" - while True: - try: - choice = int(input("Enter choice (1 or 2): ")) - if choice in [1, 2]: - return choice - else: - print("❌ Please enter 1 or 2.") - except ValueError: - print("❌ Invalid input. Please enter a number.") - -def main(): - """Main program function.""" - print("🌡️ Temperature Converter 🌡️") - print("=" * 30) - print("What conversion do you want?") - print("1. Celsius to Fahrenheit") - print("2. Fahrenheit to Celsius") - - choice = get_menu_choice() - - if choice == 1: - # Celsius to Fahrenheit - celsius = get_temperature_input("Enter temperature in Celsius: ") - fahrenheit = celsius_to_fahrenheit(celsius) - print(".1f") - elif choice == 2: - # Fahrenheit to Celsius - fahrenheit = get_temperature_input("Enter temperature in Fahrenheit: ") - celsius = fahrenheit_to_celsius(fahrenheit) - print(".1f") -if __name__ == "__main__": - main() -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard python conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/python/stage-4/level-2/lesson.md b/lessons/python/stage-4/level-2/lesson.md index b09d036..9662918 100644 --- a/lessons/python/stage-4/level-2/lesson.md +++ b/lessons/python/stage-4/level-2/lesson.md @@ -39,24 +39,24 @@ The data processor should handle: ### How to Run 1. **Navigate to this level's directory**: - ```bash + ``` cd python/stage-4-full-problem-solving/level-2-data-processing-application - ```bash + ``` 2. **Create a sample data file** (or use the provided one): - ```bash + ``` # Create sample_data.txt Name,Age,City,Salary John,25,New York,50000 Jane,30,London,60000 Bob,35,Paris,55000 Alice,28,Berlin,52000 - ```python + ``` 3. **Run the program**: - ```bash + ``` python3 main.py - ```python + ``` 4. **Test all menu options** with your data @@ -103,11 +103,11 @@ Try these advanced features: ### Key Data Structures -```python +``` # Global data storage data = [] # List of lists containing the actual data rows headers = [] # List of column headers -```python +``` - **`data`**: Each inner list represents one row of data - **`headers`**: Column names corresponding to data columns @@ -115,11 +115,11 @@ headers = [] # List of column headers ### File I/O Operations -```python +``` def load_data(filename): with open(filename, 'r') as file: lines = file.readlines() -```python +``` - **Context Manager**: `with` statement ensures file is properly closed - **Read All Lines**: `readlines()` gives us a list of all lines @@ -127,14 +127,14 @@ def load_data(filename): ### Data Processing Functions -```python +``` def filter_data(): # Find records matching criteria filtered_data = [] for row in data: if col_choice < len(row) and str(row[col_choice]) == filter_value: filtered_data.append(row) -```python +``` - **List Comprehension Alternative**: Could use `[row for row in data if condition]` - **Data Integrity**: Checks ensure we don't access invalid indices @@ -142,7 +142,7 @@ def filter_data(): ### Statistical Calculations -```python +``` def calculate_stats(): values = [] for row in data: @@ -150,7 +150,7 @@ def calculate_stats(): values.append(float(row[col_idx])) except ValueError: continue -```python +``` - **Type Safety**: Try/except handles non-numeric data gracefully - **Robust Statistics**: Only processes valid numeric values @@ -167,11 +167,11 @@ def calculate_stats(): ### Data Format Specification **CSV-like Format Requirements:** -```python +``` Header1,Header2,Header3,... Value1,Value2,Value3,... Value1,Value2,Value3,... -```python +``` - **Header Row**: First line contains column names - **Data Rows**: Subsequent lines contain data values @@ -192,21 +192,21 @@ Value1,Value2,Value3,... ### Algorithm Analysis **Sorting Implementation:** -```python +``` data.sort(key=lambda row: row[col_choice] if col_choice < len(row) else "", reverse=reverse) -```python +``` - **Lambda Function**: Anonymous function for sort key - **Safety Check**: Prevents index errors with conditional - **String Sorting**: Default string comparison for mixed data **Statistics Calculation:** -```python +``` total = sum(values) average = total / len(values) minimum = min(values) maximum = max(values) -```python +``` - **Built-in Functions**: Python's `sum()`, `min()`, `max()` are efficient - **Single Pass**: All statistics calculated in one iteration @@ -240,7 +240,7 @@ maximum = max(values) --- - **Excellent! You now understand data processing fundamentals!** + **Excellent! You now understand data processing fundamentals!** *Next up: Mathematical Application - building calculators and solvers!* @@ -260,309 +260,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```py -#!/usr/bin/env python3 -""" -Simple Data Processor -A Python program for loading, processing, and analyzing tabular data. -""" - -import os - -# Global data storage -data = [] -headers = [] - -def load_data(filename): - """Load data from a CSV-like file.""" - global data, headers - - if not os.path.exists(filename): - print(f"❌ File '{filename}' not found!") - return False - - try: - with open(filename, 'r') as file: - lines = file.readlines() - - if not lines: - print("❌ File is empty!") - return False - - # Parse headers - headers = [col.strip() for col in lines[0].split(',')] - - # Parse data rows - data = [] - for line in lines[1:]: - if line.strip(): # Skip empty lines - row = [col.strip() for col in line.split(',')] - if len(row) == len(headers): - data.append(row) - else: - print(f"⚠️ Skipping malformed row: {line.strip()}") - - print(f"✅ Data loaded successfully! ({len(data)} records)") - return True - - except Exception as e: - print(f"❌ Error loading file: {e}") - return False - -def display_data(): - """Display data in tabular format.""" - if not data: - print("❌ No data loaded. Please load a data file first.") - return - - # Calculate column widths - col_widths = [] - for i, header in enumerate(headers): - max_width = len(header) - for row in data: - if i < len(row): - max_width = max(max_width, len(str(row[i]))) - col_widths.append(max_width) - - # Print headers - header_line = "" - for i, header in enumerate(headers): - header_line += f"{header:<{col_widths[i]}} " - print(header_line) - print("-" * len(header_line)) - - # Print data rows - for row in data: - row_line = "" - for i, cell in enumerate(row): - if i < len(col_widths): - row_line += f"{cell:<{col_widths[i]}} " - print(row_line) - -def filter_data(): - """Filter data based on user criteria.""" - if not data: - print("❌ No data loaded. Please load a data file first.") - return - - print("Available columns:") - for i, header in enumerate(headers): - print(f"{i+1}. {header}") - - try: - col_choice = int(input("Choose column to filter by (number): ")) - 1 - if col_choice < 0 or col_choice >= len(headers): - print("❌ Invalid column choice!") - return - - filter_value = input(f"Enter value to filter for in '{headers[col_choice]}': ") - - filtered_data = [] - for row in data: - if col_choice < len(row) and str(row[col_choice]) == filter_value: - filtered_data.append(row) - - print(f"\nFiltered Results ({len(filtered_data)} matches):") - if filtered_data: - # Temporarily replace data for display - original_data = data[:] - data[:] = filtered_data - display_data() - data[:] = original_data - else: - print("No matching records found.") - - except ValueError: - print("❌ Invalid input. Please enter a number.") - -def sort_data(): - """Sort data by a specified column.""" - if not data: - print("❌ No data loaded. Please load a data file first.") - return - - print("Available columns:") - for i, header in enumerate(headers): - print(f"{i+1}. {header}") - - try: - col_choice = int(input("Choose column to sort by (number): ")) - 1 - if col_choice < 0 or col_choice >= len(headers): - print("❌ Invalid column choice!") - return - - reverse = input("Sort ascending? (y/n): ").lower() == 'n' - - # Sort data - data.sort(key=lambda row: row[col_choice] if col_choice < len(row) else "", reverse=reverse) - - print(f"✅ Data sorted by '{headers[col_choice]}' ({'descending' if reverse else 'ascending'})") - display_data() - - except ValueError: - print("❌ Invalid input. Please enter a number.") - -def calculate_stats(): - """Calculate statistics for numeric columns.""" - if not data: - print("❌ No data loaded. Please load a data file first.") - return - - # Find numeric columns - numeric_cols = [] - for i, header in enumerate(headers): - # Check if column contains numeric data - is_numeric = True - for row in data: - if i < len(row): - try: - float(row[i]) - except ValueError: - is_numeric = False - break - if is_numeric: - numeric_cols.append(i) - - if not numeric_cols: - print("❌ No numeric columns found in the data.") - return - - print("Numeric columns available:") - for i, col_idx in enumerate(numeric_cols): - print(f"{i+1}. {headers[col_idx]}") - - try: - col_choice = int(input("Choose column for statistics (number): ")) - 1 - if col_choice < 0 or col_choice >= len(numeric_cols): - print("❌ Invalid column choice!") - return - - col_idx = numeric_cols[col_choice] - values = [] - - for row in data: - if col_idx < len(row): - try: - values.append(float(row[col_idx])) - except ValueError: - continue - - if not values: - print("❌ No valid numeric values found in column.") - return - - total = sum(values) - average = total / len(values) - minimum = min(values) - maximum = max(values) - - print(f"\nStatistics for '{headers[col_idx]}':") - print(f"Count: {len(values)}") - print(f"Sum: {total:.2f}") - print(f"Average: {average:.2f}") - print(f"Minimum: {minimum:.2f}") - print(f"Maximum: {maximum:.2f}") - - except ValueError: - print("❌ Invalid input. Please enter a number.") - -def export_data(): - """Export current data to a file.""" - if not data: - print("❌ No data to export. Please load data first.") - return - - filename = input("Enter export filename: ") - if not filename.endswith('.txt'): - filename += '.txt' - - try: - with open(filename, 'w') as file: - # Write headers - file.write(','.join(headers) + '\n') - - # Write data - for row in data: - file.write(','.join(row) + '\n') - - print(f"✅ Data exported to '{filename}' successfully!") - - except Exception as e: - print(f"❌ Error exporting data: {e}") - -def main(): - """Main program function.""" - print("📊 Simple Data Processor 📊") - print("=" * 30) - - while True: - print("\nData Operations Menu:") - print("1. Load Data File") - print("2. View Data") - print("3. Filter Data") - print("4. Sort Data") - print("5. Calculate Statistics") - print("6. Export Data") - print("7. Exit") - - try: - choice = int(input("Enter choice (1-7): ")) - - if choice == 1: - filename = input("Enter filename: ") - load_data(filename) - elif choice == 2: - display_data() - elif choice == 3: - filter_data() - elif choice == 4: - sort_data() - elif choice == 5: - calculate_stats() - elif choice == 6: - export_data() - elif choice == 7: - print("\nThank you for using the Simple Data Processor! 📊") - break - else: - print("❌ Invalid choice. Please enter 1-7.") - - except ValueError: - print("❌ Invalid input. Please enter a number.") - -if __name__ == "__main__": - main() -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard python conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/python/stage-4/level-3/lesson.md b/lessons/python/stage-4/level-3/lesson.md index e584b12..c00d389 100644 --- a/lessons/python/stage-4/level-3/lesson.md +++ b/lessons/python/stage-4/level-3/lesson.md @@ -38,14 +38,14 @@ The calculator should provide: ### How to Run 1. **Navigate to this level's directory**: - ```bash + ``` cd python/stage-4-full-problem-solving/level-3-mathematical-application - ```bash + ``` 2. **Run the program**: - ```bash + ``` python3 main.py - ```bash + ``` 3. **Test all calculator functions** and explore the features @@ -91,7 +91,7 @@ Try these advanced mathematical features: ### Mathematical Operations Implementation -```python +``` import math # Basic operations @@ -103,7 +103,7 @@ result = math.sqrt(num) # Square root result = math.factorial(int(num)) # Factorial result = math.log(num) # Natural logarithm result = math.exp(num) # Exponential -```python +``` - **Built-in Operators**: Python provides `+`, `-`, `*`, `/`, `**` directly - **Math Module**: `import math` gives access to advanced functions @@ -111,14 +111,14 @@ result = math.exp(num) # Exponential ### Trigonometric Functions -```python +``` # Convert degrees to radians for math functions angle_rad = math.radians(angle) result = math.sin(angle_rad) # Convert back to degrees for inverse functions result = math.degrees(math.asin(value)) -```python +``` - **Radian Conversion**: Math functions expect radians, not degrees - **Inverse Functions**: asin, acos, atan return radians, convert back to degrees @@ -126,7 +126,7 @@ result = math.degrees(math.asin(value)) ### State Management -```python +``` # Global variables for persistent state memory = 0.0 history = [] @@ -134,7 +134,7 @@ history = [] def add_to_history(operation, result): """Add calculation to history.""" history.append(f"{operation} = {result}") -```python +``` - **Global State**: Variables accessible across function calls - **Data Persistence**: History maintained throughout program execution @@ -170,7 +170,7 @@ def add_to_history(operation, result): ### Input Validation Patterns -```python +``` def validate_number(prompt): """Get a valid number from user input.""" while True: @@ -179,7 +179,7 @@ def validate_number(prompt): return num except ValueError: print(" Invalid input. Please enter a valid number.") -```python +``` - **Loop Until Valid**: Keeps prompting until good input received - **Type Conversion**: `float()` handles both integers and decimals @@ -187,7 +187,7 @@ def validate_number(prompt): ### Memory and History Implementation -```python +``` # Memory operations memory = 0.0 @@ -196,7 +196,7 @@ def memory_functions(): memory = value elif choice == '2': # Recall print(f"Memory: {memory}") -```python +``` - **Persistent Storage**: Memory retains value between operations - **Multiple Operations**: Store, recall, add, subtract, clear @@ -204,7 +204,7 @@ def memory_functions(): ### Menu System Design -```python +``` while True: print_menu() choice = get_choice() @@ -213,7 +213,7 @@ while True: basic_calculator() elif choice == '7': break -```python +``` - **Main Loop**: Continues until user chooses to exit - **Modular Functions**: Each menu option calls separate function @@ -222,7 +222,7 @@ while True: --- - **Outstanding! You now have a professional calculator application!** + **Outstanding! You now have a professional calculator application!** *Next up: Interactive Application - building user-focused programs!* @@ -242,307 +242,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```py -#!/usr/bin/env python3 -""" -Advanced Calculator -A comprehensive calculator with basic and advanced mathematical operations. -""" - -import math - -# Global variables for memory and history -memory = 0.0 -history = [] - -def validate_number(prompt): - """Get a valid number from user input.""" - while True: - try: - num = float(input(prompt)) - return num - except ValueError: - print("❌ Invalid input. Please enter a valid number.") - -def add_to_history(operation, result): - """Add calculation to history.""" - history.append(f"{operation} = {result}") - -def basic_calculator(): - """Handle basic arithmetic operations.""" - print("\nBasic Calculator (+, -, *, /)") - - num1 = validate_number("Enter first number: ") - - operation = input("Enter operation (+, -, *, /): ").strip() - - if operation not in ['+', '-', '*', '/']: - print("❌ Invalid operation. Please use +, -, *, or /.") - return - - num2 = validate_number("Enter second number: ") - - if operation == '/' and num2 == 0: - print("❌ Division by zero is not allowed!") - return - - # Perform calculation - result = 0.0 - if operation == '+': - result = num1 + num2 - elif operation == '-': - result = num1 - num2 - elif operation == '*': - result = num1 * num2 - elif operation == '/': - result = num1 / num2 - - operation_str = f"{num1} {operation} {num2}" - print(f"Result: {operation_str} = {result}") - - add_to_history(operation_str, result) - - # Memory option - store_memory = input("Add to memory? (y/n): ").lower().strip() - if store_memory == 'y': - global memory - memory = result - print("✅ Result stored in memory!") - -def advanced_operations(): - """Handle advanced mathematical operations.""" - print("\nAdvanced Operations") - print("1. Power (x^y)") - print("2. Square Root (√x)") - print("3. Factorial (x!)") - print("4. Natural Logarithm (ln x)") - print("5. Exponential (e^x)") - - choice = input("Enter choice (1-5): ").strip() - - if choice == '1': - # Power - base = validate_number("Enter base: ") - exponent = validate_number("Enter exponent: ") - result = base ** exponent - operation_str = f"{base}^{exponent}" - print(f"Result: {operation_str} = {result}") - add_to_history(operation_str, result) - - elif choice == '2': - # Square root - num = validate_number("Enter number: ") - if num < 0: - print("❌ Cannot calculate square root of negative number!") - return - result = math.sqrt(num) - operation_str = f"√{num}" - print(f"Result: {operation_str} = {result}") - add_to_history(operation_str, result) - - elif choice == '3': - # Factorial - num = validate_number("Enter integer: ") - if num < 0 or not num.is_integer(): - print("❌ Factorial requires non-negative integer!") - return - result = math.factorial(int(num)) - operation_str = f"{int(num)}!" - print(f"Result: {operation_str} = {result}") - add_to_history(operation_str, result) - - elif choice == '4': - # Natural logarithm - num = validate_number("Enter positive number: ") - if num <= 0: - print("❌ Natural logarithm requires positive number!") - return - result = math.log(num) - operation_str = f"ln({num})" - print(f"Result: {operation_str} = {result:.6f}") - add_to_history(operation_str, result) - - elif choice == '5': - # Exponential - num = validate_number("Enter exponent: ") - result = math.exp(num) - operation_str = f"e^{num}" - print(f"Result: {operation_str} = {result:.6f}") - add_to_history(operation_str, result) - - else: - print("❌ Invalid choice!") - return - -def trigonometric_functions(): - """Handle trigonometric functions.""" - print("\nTrigonometric Functions") - print("1. Sine (sin x)") - print("2. Cosine (cos x)") - print("3. Tangent (tan x)") - print("4. Arcsine (asin x)") - print("5. Arccosine (acos x)") - print("6. Arctangent (atan x)") - - choice = input("Enter choice (1-6): ").strip() - angle = validate_number("Enter angle in degrees: ") - - # Convert to radians for calculation - angle_rad = math.radians(angle) - result = 0.0 - operation_str = "" - - if choice == '1': - result = math.sin(angle_rad) - operation_str = f"sin({angle}°)" - elif choice == '2': - result = math.cos(angle_rad) - operation_str = f"cos({angle}°)" - elif choice == '3': - result = math.tan(angle_rad) - operation_str = f"tan({angle}°)" - elif choice == '4': - if not -1 <= angle <= 1: - print("❌ Arcsine requires value between -1 and 1!") - return - result = math.degrees(math.asin(angle)) - operation_str = f"asin({angle})" - elif choice == '5': - if not -1 <= angle <= 1: - print("❌ Arccosine requires value between -1 and 1!") - return - result = math.degrees(math.acos(angle)) - operation_str = f"acos({angle})" - elif choice == '6': - result = math.degrees(math.atan(angle)) - operation_str = f"atan({angle})" - else: - print("❌ Invalid choice!") - return - - print(f"Result: {operation_str} = {result:.6f}") - add_to_history(operation_str, result) - -def memory_functions(): - """Handle memory operations.""" - print("\nMemory Functions") - print("1. Store Value") - print("2. Recall Value") - print("3. Clear Memory") - print("4. Add to Memory") - print("5. Subtract from Memory") - - choice = input("Enter choice (1-5): ").strip() - - if choice == '1': - value = validate_number("Enter value to store: ") - global memory - memory = value - print(f"✅ Stored {value} in memory") - elif choice == '2': - print(f"Memory value: {memory}") - elif choice == '3': - memory = 0.0 - print("✅ Memory cleared") - elif choice == '4': - value = validate_number("Enter value to add: ") - memory += value - print(f"✅ Added {value}. New memory value: {memory}") - elif choice == '5': - value = validate_number("Enter value to subtract: ") - memory -= value - print(f"✅ Subtracted {value}. New memory value: {memory}") - else: - print("❌ Invalid choice!") - -def view_history(): - """Display calculation history.""" - print("\nCalculation History") - print("=" * 20) - - if not history: - print("No calculations in history.") - return - - for i, calc in enumerate(history, 1): - print(f"{i}. {calc}") - -def clear_history(): - """Clear calculation history.""" - global history - history.clear() - print("✅ Calculation history cleared!") - -def main(): - """Main program function.""" - print("🧮 Advanced Calculator 🧮") - print("=" * 25) - - while True: - print("\nOperations Menu:") - print("1. Basic Calculator (+, -, *, /)") - print("2. Advanced Operations (^, √, !)") - print("3. Trigonometric Functions") - print("4. Memory Functions") - print("5. View History") - print("6. Clear History") - print("7. Exit") - - choice = input("Enter choice (1-7): ").strip() - - if choice == '1': - basic_calculator() - elif choice == '2': - advanced_operations() - elif choice == '3': - trigonometric_functions() - elif choice == '4': - memory_functions() - elif choice == '5': - view_history() - elif choice == '6': - clear_history() - elif choice == '7': - print("\nThank you for using the Advanced Calculator! 🧮") - break - else: - print("❌ Invalid choice. Please enter 1-7.") - - input("\nPress Enter to continue...") - -if __name__ == "__main__": - main() -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard python conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/python/stage-4/level-4/lesson.md b/lessons/python/stage-4/level-4/lesson.md index 44f0c9e..09a364c 100644 --- a/lessons/python/stage-4/level-4/lesson.md +++ b/lessons/python/stage-4/level-4/lesson.md @@ -27,13 +27,13 @@ The Task Manager application consists of: ### Key Components **Task Data Structure:** -```python +``` task = { 'id': self.next_id, 'description': description, 'completed': False } -```python +``` Each task is stored as a dictionary with an ID, description, and completion status. **Menu System:** @@ -144,170 +144,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```py -#!/usr/bin/env python3 -""" -Interactive Task Manager Application -A simple command-line task management system with menu-driven interface. -""" - -class TaskManager: - def __init__(self): - self.tasks = [] - self.next_id = 1 - - def add_task(self, description): - """Add a new task to the list.""" - task = { - 'id': self.next_id, - 'description': description, - 'completed': False - } - self.tasks.append(task) - self.next_id += 1 - print(f"Task '{description}' added successfully!") - - def view_tasks(self): - """Display all tasks with their status.""" - if not self.tasks: - print("No tasks found.") - return - - print("\nCurrent Tasks:") - print("-" * 40) - for task in self.tasks: - status = "[✓]" if task['completed'] else "[ ]" - print(f"{task['id']}. {status} {task['description']}") - print("-" * 40) - - def complete_task(self, task_id): - """Mark a task as completed.""" - for task in self.tasks: - if task['id'] == task_id: - if task['completed']: - print(f"Task {task_id} is already completed.") - else: - task['completed'] = True - print(f"Task '{task['description']}' marked as completed!") - return - print(f"Task with ID {task_id} not found.") - - def delete_task(self, task_id): - """Delete a task from the list.""" - for i, task in enumerate(self.tasks): - if task['id'] == task_id: - removed_task = self.tasks.pop(i) - print(f"Task '{removed_task['description']}' deleted successfully!") - return - print(f"Task with ID {task_id} not found.") - -def display_menu(): - """Display the main menu options.""" - print("\n" + "="*50) - print(" INTERACTIVE TASK MANAGER") - print("="*50) - print("1. Add a new task") - print("2. View all tasks") - print("3. Complete a task") - print("4. Delete a task") - print("5. Exit") - print("="*50) - -def get_user_choice(): - """Get and validate user's menu choice.""" - while True: - try: - choice = int(input("Enter your choice (1-5): ")) - if 1 <= choice <= 5: - return choice - else: - print("Please enter a number between 1 and 5.") - except ValueError: - print("Please enter a valid number.") - -def main(): - """Main application loop.""" - manager = TaskManager() - - print("Welcome to the Interactive Task Manager!") - print("Manage your tasks efficiently with this simple application.") - - while True: - display_menu() - choice = get_user_choice() - - if choice == 1: - description = input("Enter task description: ").strip() - if description: - manager.add_task(description) - else: - print("Task description cannot be empty.") - - elif choice == 2: - manager.view_tasks() - - elif choice == 3: - if not manager.tasks: - print("No tasks available to complete.") - continue - manager.view_tasks() - try: - task_id = int(input("Enter task ID to complete: ")) - manager.complete_task(task_id) - except ValueError: - print("Please enter a valid task ID.") - - elif choice == 4: - if not manager.tasks: - print("No tasks available to delete.") - continue - manager.view_tasks() - try: - task_id = int(input("Enter task ID to delete: ")) - manager.delete_task(task_id) - except ValueError: - print("Please enter a valid task ID.") - - elif choice == 5: - print("Thank you for using the Task Manager. Goodbye!") - break - - # Pause before showing menu again - input("\nPress Enter to continue...") - -if __name__ == "__main__": - main() -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard python conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/python/stage-4/level-5/lesson.md b/lessons/python/stage-4/level-5/lesson.md index 6b2c0e1..d09255c 100644 --- a/lessons/python/stage-4/level-5/lesson.md +++ b/lessons/python/stage-4/level-5/lesson.md @@ -39,9 +39,9 @@ The system uses conditional logic to map user responses to specific recommendati - Time availability sets scheduling recommendations **Data Flow:** -```python +``` User Input → Assessment → Analysis → Recommendation → Display -```python +``` ### Decision-Making Algorithm @@ -141,207 +141,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```py -#!/usr/bin/env python3 -""" -Study Plan Advisor - Decision Support Application -A simple expert system that recommends study plans based on user preferences and goals. -""" - -def get_user_input(prompt, options): - """Get validated user input from a list of options.""" - while True: - print(f"\n{prompt}") - for i, option in enumerate(options, 1): - print(f"{i}. {option}") - - try: - choice = int(input("Enter your choice (number): ")) - if 1 <= choice <= len(options): - return options[choice - 1] - else: - print(f"Please enter a number between 1 and {len(options)}.") - except ValueError: - print("Please enter a valid number.") - -def assess_learning_style(): - """Assess the user's preferred learning style.""" - print("Let's determine your learning style!") - - question1 = "How do you prefer to learn new information?" - options1 = [ - "By reading books or articles", - "By watching videos or demonstrations", - "By doing hands-on activities", - "By discussing with others" - ] - style = get_user_input(question1, options1) - - question2 = "When studying, you prefer:" - options2 = [ - "Structured schedules and outlines", - "Flexible, exploratory approach", - "Group study sessions", - "Independent, focused work" - ] - preference = get_user_input(question2, options2) - - return style, preference - -def assess_goals_and_time(): - """Assess user's goals and available time.""" - print("\nNow let's understand your goals and schedule!") - - question3 = "What is your primary learning goal?" - options3 = [ - "Master a specific skill", - "Gain broad knowledge in a field", - "Prepare for certification/exam", - "Personal development" - ] - goal = get_user_input(question3, options3) - - question4 = "How much time can you dedicate daily?" - options4 = [ - "Less than 1 hour", - "1-2 hours", - "2-4 hours", - "More than 4 hours" - ] - time_available = get_user_input(question4, options4) - - return goal, time_available - -def generate_recommendation(style, preference, goal, time_available): - """Generate a personalized study plan recommendation.""" - print("\n" + "="*60) - print(" YOUR PERSONALIZED STUDY PLAN") - print("="*60) - - # Base recommendation - plan = { - 'focus': '', - 'methods': [], - 'schedule': '', - 'tips': [] - } - - # Determine focus based on goal - if goal == "Master a specific skill": - plan['focus'] = "Skill-focused intensive practice" - elif goal == "Gain broad knowledge in a field": - plan['focus'] = "Comprehensive knowledge building" - elif goal == "Prepare for certification/exam": - plan['focus'] = "Exam-oriented structured preparation" - else: # Personal development - plan['focus'] = "Well-rounded personal growth" - - # Determine methods based on learning style - if style == "By reading books or articles": - plan['methods'].extend(["Reading textbooks", "Writing summaries", "Research papers"]) - elif style == "By watching videos or demonstrations": - plan['methods'].extend(["Online video tutorials", "Interactive demonstrations", "Recorded lectures"]) - elif style == "By doing hands-on activities": - plan['methods'].extend(["Practical exercises", "Projects", "Experiments"]) - else: # By discussing with others - plan['methods'].extend(["Study groups", "Discussion forums", "Teaching others"]) - - # Adjust for preference - if preference == "Structured schedules and outlines": - plan['methods'].append("Detailed planning and checklists") - elif preference == "Flexible, exploratory approach": - plan['methods'].append("Exploratory learning and curiosity-driven research") - elif preference == "Group study sessions": - plan['methods'].append("Collaborative learning activities") - else: # Independent, focused work - plan['methods'].append("Solo deep work sessions") - - # Determine schedule based on time - if time_available == "Less than 1 hour": - plan['schedule'] = "15-30 minute focused sessions, 4-6 days per week" - elif time_available == "1-2 hours": - plan['schedule'] = "1-2 hour daily sessions with weekends off" - elif time_available == "2-4 hours": - plan['schedule'] = "2-3 hour intensive daily study blocks" - else: # More than 4 hours - plan['schedule'] = "4+ hour comprehensive daily study with breaks" - - # Add general tips - plan['tips'] = [ - "Track your progress weekly", - "Review material regularly for retention", - "Take breaks to avoid burnout", - "Adjust plan as needed based on progress" - ] - - return plan - -def display_recommendation(plan): - """Display the study plan recommendation.""" - print(f"\nFocus: {plan['focus']}") - print(f"\nRecommended Schedule: {plan['schedule']}") - - print("\nStudy Methods:") - for i, method in enumerate(plan['methods'], 1): - print(f" {i}. {method}") - - print("\nAdditional Tips:") - for i, tip in enumerate(plan['tips'], 1): - print(f" {i}. {tip}") - - print("\n" + "="*60) - print("Remember: This is a starting point. Adjust based on your experience!") - print("="*60) - -def main(): - """Main application function.""" - print("Welcome to the Study Plan Advisor!") - print("Answer a few questions and get a personalized study plan recommendation.") - - # Get user preferences - style, preference = assess_learning_style() - goal, time_available = assess_goals_and_time() - - # Generate and display recommendation - plan = generate_recommendation(style, preference, goal, time_available) - display_recommendation(plan) - - print("\nThank you for using the Study Plan Advisor!") - input("Press Enter to exit...") - -if __name__ == "__main__": - main() -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard python conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/python/stage-4/level-6/lesson.md b/lessons/python/stage-4/level-6/lesson.md index 2ccefbf..09ae5fc 100644 --- a/lessons/python/stage-4/level-6/lesson.md +++ b/lessons/python/stage-4/level-6/lesson.md @@ -29,13 +29,13 @@ The File Organizer demonstrates automated processing: ### Key Components **File Categorization System:** -```python +``` self.categories = { 'Documents': ['.pdf', '.doc', '.docx', ...], 'Images': ['.jpg', '.jpeg', '.png', ...], # ... } -```python +``` Uses a dictionary to map file extensions to organizational categories. **Path Handling:** @@ -45,11 +45,11 @@ Utilizes Python's `pathlib` for cross-platform file operations: - Safe handling of different operating systems **Command-Line Interface:** -```python +``` parser = argparse.ArgumentParser(description='Automatically organize files by type') parser.add_argument('directory', help='Directory to organize') parser.add_argument('--dry-run', action='store_true', help='Show what would be done') -```bash +``` ### Automation Principles @@ -153,207 +153,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```py -#!/usr/bin/env python3 -""" -Automated File Organizer -A script that automatically organizes files in a directory based on their file types. -""" - -import os -import shutil -from pathlib import Path -import argparse -import sys - -class FileOrganizer: - def __init__(self, target_directory, dry_run=False): - self.target_directory = Path(target_directory) - self.dry_run = dry_run - self.stats = { - 'files_processed': 0, - 'files_moved': 0, - 'directories_created': 0, - 'errors': 0 - } - - # Define file type categories and their extensions - self.categories = { - 'Documents': ['.pdf', '.doc', '.docx', '.txt', '.rtf', '.odt', '.xls', '.xlsx', '.ppt', '.pptx'], - 'Images': ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.svg', '.webp', '.ico'], - 'Videos': ['.mp4', '.avi', '.mkv', '.mov', '.wmv', '.flv', '.webm', '.m4v'], - 'Music': ['.mp3', '.wav', '.flac', '.aac', '.ogg', '.wma', '.m4a'], - 'Archives': ['.zip', '.rar', '.7z', '.tar', '.gz', '.bz2', '.xz'], - 'Code': ['.py', '.js', '.html', '.css', '.java', '.cpp', '.c', '.php', '.rb', '.go', '.rs'], - 'Executables': ['.exe', '.msi', '.dmg', '.app', '.deb', '.rpm'], - 'Others': [] # Catch-all for unrecognized extensions - } - - def get_category(self, file_path): - """Determine the category for a file based on its extension.""" - extension = file_path.suffix.lower() - - for category, extensions in self.categories.items(): - if extension in extensions: - return category - - return 'Others' - - def create_category_directory(self, category): - """Create a directory for the specified category if it doesn't exist.""" - category_dir = self.target_directory / category - - if not category_dir.exists(): - if not self.dry_run: - try: - category_dir.mkdir(parents=True, exist_ok=True) - print(f"Created directory: {category_dir}") - except Exception as e: - print(f"Error creating directory {category_dir}: {e}") - self.stats['errors'] += 1 - return None - else: - print(f"Would create directory: {category_dir}") - - self.stats['directories_created'] += 1 - - return category_dir - - def move_file(self, source_path, destination_dir): - """Move a file to the destination directory.""" - filename = source_path.name - destination_path = destination_dir / filename - - # Handle filename conflicts - counter = 1 - while destination_path.exists(): - stem = source_path.stem - suffix = source_path.suffix - new_filename = f"{stem}_{counter}{suffix}" - destination_path = destination_dir / new_filename - counter += 1 - - if not self.dry_run: - try: - shutil.move(str(source_path), str(destination_path)) - print(f"Moved: {source_path} → {destination_path}") - except Exception as e: - print(f"Error moving {source_path}: {e}") - self.stats['errors'] += 1 - return False - else: - print(f"Would move: {source_path} → {destination_path}") - - self.stats['files_moved'] += 1 - return True - - def organize_files(self): - """Main method to organize all files in the target directory.""" - if not self.target_directory.exists(): - print(f"Error: Directory '{self.target_directory}' does not exist.") - return False - - if not self.target_directory.is_dir(): - print(f"Error: '{self.target_directory}' is not a directory.") - return False - - print(f"Starting file organization in: {self.target_directory}") - if self.dry_run: - print("DRY RUN MODE - No files will be moved") - print("-" * 50) - - # Get all files in the directory (not subdirectories) - files = [f for f in self.target_directory.iterdir() if f.is_file()] - - if not files: - print("No files found to organize.") - return True - - for file_path in files: - self.stats['files_processed'] += 1 - - # Skip the script itself if it's in the target directory - if file_path.name == 'main.py': - continue - - category = self.get_category(file_path) - category_dir = self.create_category_directory(category) - - if category_dir: - self.move_file(file_path, category_dir) - - return True - - def print_summary(self): - """Print a summary of the organization process.""" - print("\n" + "="*50) - print("ORGANIZATION SUMMARY") - print("="*50) - print(f"Files processed: {self.stats['files_processed']}") - print(f"Files moved: {self.stats['files_moved']}") - print(f"Directories created: {self.stats['directories_created']}") - print(f"Errors encountered: {self.stats['errors']}") - - if self.dry_run: - print("\nThis was a dry run. No files were actually moved.") - print("Run without --dry-run to perform the actual organization.") - else: - print("\nFile organization completed successfully!") - -def main(): - """Main application entry point.""" - parser = argparse.ArgumentParser(description='Automatically organize files by type') - parser.add_argument('directory', help='Directory to organize') - parser.add_argument('--dry-run', action='store_true', - help='Show what would be done without making changes') - - args = parser.parse_args() - - # If no directory provided, use current directory - if not args.directory: - args.directory = '.' - - organizer = FileOrganizer(args.directory, args.dry_run) - - success = organizer.organize_files() - organizer.print_summary() - - if not success: - sys.exit(1) - -if __name__ == "__main__": - main() -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard python conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/python/stage-4/level-7/lesson.md b/lessons/python/stage-4/level-7/lesson.md index 12a4719..d79509a 100644 --- a/lessons/python/stage-4/level-7/lesson.md +++ b/lessons/python/stage-4/level-7/lesson.md @@ -42,9 +42,9 @@ The Personal Finance Manager demonstrates full-stack application development: - **Automated Processing**: Report generation and budget alert checking **Data Flow:** -```python +``` User Input → Validation → Business Logic → Data Storage → UI Feedback -```python +``` ### Advanced Concepts @@ -172,319 +172,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```py -#!/usr/bin/env python3 -""" -Personal Finance Manager - Capstone Project -A comprehensive personal finance management application combining multiple features. -""" - -import json -import os -from datetime import datetime, timedelta -from collections import defaultdict -import statistics - -class Transaction: - def __init__(self, amount, category, description, date=None): - self.amount = float(amount) - self.category = category - self.description = description - self.date = date or datetime.now().strftime('%Y-%m-%d') - - def to_dict(self): - return { - 'amount': self.amount, - 'category': self.category, - 'description': self.description, - 'date': self.date - } - - @classmethod - def from_dict(cls, data): - return cls(data['amount'], data['category'], data['description'], data['date']) - -class FinanceManager: - def __init__(self, data_file='finance_data.json'): - self.data_file = data_file - self.transactions = [] - self.budgets = {} - self.load_data() - - def load_data(self): - """Load transactions and budgets from file.""" - if os.path.exists(self.data_file): - try: - with open(self.data_file, 'r') as f: - data = json.load(f) - self.transactions = [Transaction.from_dict(t) for t in data.get('transactions', [])] - self.budgets = data.get('budgets', {}) - except Exception as e: - print(f"Error loading data: {e}") - - def save_data(self): - """Save transactions and budgets to file.""" - data = { - 'transactions': [t.to_dict() for t in self.transactions], - 'budgets': self.budgets - } - try: - with open(self.data_file, 'w') as f: - json.dump(data, f, indent=2) - except Exception as e: - print(f"Error saving data: {e}") - - def add_transaction(self, amount, category, description): - """Add a new transaction.""" - transaction = Transaction(amount, category, description) - self.transactions.append(transaction) - self.save_data() - print(f"Transaction added: {description} - ${amount:.2f}") - - def get_balance(self): - """Calculate current balance.""" - return sum(t.amount for t in self.transactions) - - def get_category_totals(self, days=30): - """Get spending totals by category for the last N days.""" - cutoff_date = datetime.now() - timedelta(days=days) - cutoff_str = cutoff_date.strftime('%Y-%m-%d') - - totals = defaultdict(float) - for transaction in self.transactions: - if transaction.date >= cutoff_str and transaction.amount < 0: - totals[transaction.category] += abs(transaction.amount) - - return dict(totals) - - def get_budget_advice(self): - """Provide personalized budget recommendations.""" - monthly_spending = self.get_category_totals(30) - total_spending = sum(monthly_spending.values()) - - if total_spending == 0: - return "No spending data available. Start tracking expenses to get budget advice." - - # Calculate recommended budget allocations - recommendations = { - 'Housing': total_spending * 0.30, - 'Food': total_spending * 0.15, - 'Transportation': total_spending * 0.15, - 'Entertainment': total_spending * 0.10, - 'Savings': total_spending * 0.20, - 'Miscellaneous': total_spending * 0.10 - } - - advice = "Based on your spending patterns, here's a recommended monthly budget:\n\n" - - for category, recommended in recommendations.items(): - actual = monthly_spending.get(category, 0) - status = "✓" if actual <= recommended else "⚠" - advice += f"{category}: ${recommended:.2f} (spent: ${actual:.2f}) {status}\n" - - return advice - - def generate_report(self): - """Generate a comprehensive financial report.""" - balance = self.get_balance() - monthly_spending = self.get_category_totals(30) - - report = f""" -FINANCIAL REPORT - {datetime.now().strftime('%B %Y')} - -CURRENT BALANCE: ${balance:.2f} - -MONTHLY SPENDING BY CATEGORY: -""" - - for category, amount in sorted(monthly_spending.items(), key=lambda x: x[1], reverse=True): - report += f" {category}: ${amount:.2f}\n" - - total_spending = sum(monthly_spending.values()) - report += f"\nTOTAL MONTHLY SPENDING: ${total_spending:.2f}" - - if monthly_spending: - avg_transaction = statistics.mean(abs(t.amount) for t in self.transactions if t.amount < 0) - report += f"\nAVERAGE TRANSACTION: ${avg_transaction:.2f}" - - return report.strip() - - def set_budget(self, category, amount): - """Set a budget for a category.""" - self.budgets[category] = float(amount) - self.save_data() - print(f"Budget set for {category}: ${amount:.2f}") - - def check_budget_alerts(self): - """Check for budget alerts.""" - alerts = [] - monthly_spending = self.get_category_totals(30) - - for category, budget in self.budgets.items(): - spent = monthly_spending.get(category, 0) - if spent > budget: - alerts.append(f"⚠ OVER BUDGET: {category} (${spent:.2f} / ${budget:.2f})") - elif spent > budget * 0.8: - alerts.append(f"⚡ NEARING LIMIT: {category} (${spent:.2f} / ${budget:.2f})") - - return alerts - -def display_menu(): - """Display the main menu.""" - print("\n" + "="*55) - print(" PERSONAL FINANCE MANAGER") - print("="*55) - print("1. Add Income") - print("2. Add Expense") - print("3. View Balance") - print("4. View Spending by Category") - print("5. Set Budget") - print("6. Get Budget Advice") - print("7. Generate Report") - print("8. View Recent Transactions") - print("9. Check Budget Alerts") - print("10. Exit") - print("="*55) - -def get_user_choice(): - """Get validated menu choice.""" - while True: - try: - choice = int(input("Enter your choice (1-10): ")) - if 1 <= choice <= 10: - return choice - print("Please enter a number between 1 and 10.") - except ValueError: - print("Please enter a valid number.") - -def add_transaction_menu(manager, is_income=True): - """Menu for adding transactions.""" - transaction_type = "income" if is_income else "expense" - - try: - amount = float(input(f"Enter {transaction_type} amount: $")) - if not is_income: - amount = -abs(amount) # Ensure expenses are negative - - category = input(f"Enter category for this {transaction_type}: ").strip() - description = input("Enter description: ").strip() - - if category and description: - manager.add_transaction(amount, category, description) - else: - print("Category and description cannot be empty.") - except ValueError: - print("Please enter a valid amount.") - -def main(): - """Main application loop.""" - manager = FinanceManager() - - print("Welcome to Personal Finance Manager!") - print("Take control of your finances with comprehensive tracking and insights.") - - while True: - # Check for budget alerts - alerts = manager.check_budget_alerts() - if alerts: - print("\nBUDGET ALERTS:") - for alert in alerts: - print(f" {alert}") - - display_menu() - choice = get_user_choice() - - if choice == 1: # Add Income - add_transaction_menu(manager, is_income=True) - - elif choice == 2: # Add Expense - add_transaction_menu(manager, is_income=False) - - elif choice == 3: # View Balance - balance = manager.get_balance() - print(f"\nCurrent Balance: ${balance:.2f}") - - elif choice == 4: # View Spending by Category - spending = manager.get_category_totals(30) - if spending: - print("\nMonthly Spending by Category:") - for category, amount in sorted(spending.items(), key=lambda x: x[1], reverse=True): - print(f" {category}: ${amount:.2f}") - else: - print("No spending data available.") - - elif choice == 5: # Set Budget - category = input("Enter category: ").strip() - try: - amount = float(input("Enter budget amount: $")) - manager.set_budget(category, amount) - except ValueError: - print("Please enter a valid amount.") - - elif choice == 6: # Get Budget Advice - advice = manager.get_budget_advice() - print(f"\n{advice}") - - elif choice == 7: # Generate Report - report = manager.generate_report() - print(f"\n{report}") - - elif choice == 8: # View Recent Transactions - if manager.transactions: - print("\nRecent Transactions (last 10):") - for transaction in manager.transactions[-10:]: - print(f" {transaction.date}: {transaction.description} - ${transaction.amount:.2f} ({transaction.category})") - else: - print("No transactions recorded yet.") - - elif choice == 9: # Check Budget Alerts - alerts = manager.check_budget_alerts() - if alerts: - print("\nCurrent Budget Alerts:") - for alert in alerts: - print(f" {alert}") - else: - print("No budget alerts at this time.") - - elif choice == 10: # Exit - print("Thank you for using Personal Finance Manager. Goodbye!") - break - - input("\nPress Enter to continue...") - -if __name__ == "__main__": - main() -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard python conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/python/stage-5/level-1/lesson.md b/lessons/python/stage-5/level-1/lesson.md index 0c9e410..a1169b2 100644 --- a/lessons/python/stage-5/level-1/lesson.md +++ b/lessons/python/stage-5/level-1/lesson.md @@ -58,14 +58,14 @@ Create a production-ready Web Scraper using Python with: ### How to Run 1. **Run the code**: - ```bash + ``` python3 hello.py - ```python + ``` **Expected output:** -```python +``` Hello, World! -```python +``` ### How to Approach This @@ -222,40 +222,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```py -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard python conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/python/stage-5/level-2/lesson.md b/lessons/python/stage-5/level-2/lesson.md index 657a493..931cf0d 100644 --- a/lessons/python/stage-5/level-2/lesson.md +++ b/lessons/python/stage-5/level-2/lesson.md @@ -58,14 +58,14 @@ Create a production-ready CLI Tool using Python with: ### How to Run 1. **Run the code**: - ```bash + ``` python3 hello.py - ```python + ``` **Expected output:** -```python +``` Hello, World! -```python +``` ### How to Approach This @@ -222,40 +222,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```py -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard python conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/python/stage-5/level-3/lesson.md b/lessons/python/stage-5/level-3/lesson.md index 0296b64..c0f174f 100644 --- a/lessons/python/stage-5/level-3/lesson.md +++ b/lessons/python/stage-5/level-3/lesson.md @@ -58,14 +58,14 @@ Create a production-ready REST API using Python with: ### How to Run 1. **Run the code**: - ```bash + ``` python3 hello.py - ```python + ``` **Expected output:** -```python +``` Hello, World! -```python +``` ### How to Approach This @@ -222,40 +222,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```py -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard python conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/python/stage-5/level-4/lesson.md b/lessons/python/stage-5/level-4/lesson.md index a831ab8..59814f2 100644 --- a/lessons/python/stage-5/level-4/lesson.md +++ b/lessons/python/stage-5/level-4/lesson.md @@ -58,14 +58,14 @@ Create a production-ready Data Visualization using Python with: ### How to Run 1. **Run the code**: - ```bash + ``` python3 hello.py - ```python + ``` **Expected output:** -```python +``` Hello, World! -```python +``` ### How to Approach This @@ -222,40 +222,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```py -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard python conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/python/stage-5/level-5/lesson.md b/lessons/python/stage-5/level-5/lesson.md index bb0e01c..e18cd7e 100644 --- a/lessons/python/stage-5/level-5/lesson.md +++ b/lessons/python/stage-5/level-5/lesson.md @@ -58,14 +58,14 @@ Create a production-ready Automated Testing using Python with: ### How to Run 1. **Run the code**: - ```bash + ``` python3 hello.py - ```python + ``` **Expected output:** -```python +``` Hello, World! -```python +``` ### How to Approach This @@ -222,40 +222,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```py -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard python conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/python/stage-5/level-6/lesson.md b/lessons/python/stage-5/level-6/lesson.md index b631b4b..f5b4b4d 100644 --- a/lessons/python/stage-5/level-6/lesson.md +++ b/lessons/python/stage-5/level-6/lesson.md @@ -58,14 +58,14 @@ Create a production-ready Performance Optimization using Python with: ### How to Run 1. **Run the code**: - ```bash + ``` python3 hello.py - ```python + ``` **Expected output:** -```python +``` Hello, World! -```python +``` ### How to Approach This @@ -222,40 +222,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```py -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard python conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/python/stage-5/level-7/lesson.md b/lessons/python/stage-5/level-7/lesson.md index 08ce4ba..3e1d350 100644 --- a/lessons/python/stage-5/level-7/lesson.md +++ b/lessons/python/stage-5/level-7/lesson.md @@ -58,14 +58,14 @@ Create a production-ready Final Capstone Project using Python with: ### How to Run 1. **Run the code**: - ```bash + ``` python3 hello.py - ```python + ``` **Expected output:** -```python +``` Hello, World! -```python +``` ### How to Approach This @@ -222,40 +222,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```py -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard python conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/r/stage-1/level-1/lesson.md b/lessons/r/stage-1/level-1/lesson.md index f4095b8..d490033 100644 --- a/lessons/r/stage-1/level-1/lesson.md +++ b/lessons/r/stage-1/level-1/lesson.md @@ -23,7 +23,7 @@ Welcome to your first R program! Today, you'll create and run your very first pr **Copy the following code EXACTLY as shown below into `main.R`** -```r +``` print("Hello, World!") ``` @@ -32,12 +32,12 @@ print("Hello, World!") ### How to Run **Method 1 (Vim - Recommended):** -```r +``` r ``` **Method 2 (Terminal):** -```bash +``` Rscript main.R ``` @@ -91,44 +91,24 @@ You just created a real R program! Here's what makes it work: --- -## ANSWER KEY (No peeking until you've tried!) - -### Code Breakdown - -The code you copied demonstrates fundamental R concepts: +## ANSWER KEY (No cheating until you've tried!) -**Key Components:** -- Syntax rules specific to R -- How data is stored and manipulated -- Input/output operations -- Program flow and structure +### Solution -### Common Errors & Solutions - -| Error | Cause | Solution | -|-------|-------|----------| -| Syntax error | Typo in code | Double-check spelling and punctuation | -| Runtime error | Code runs but crashes | Check your logic and data types | -| Unexpected output | Logic error | Review your algorithm step-by-step | +``` +print("Hello, World!") +``` -### Bonus Knowledge +### Explanation -- R has a rich ecosystem of libraries and tools -- Understanding these basics prepares you for advanced topics -- Practice is key - try writing similar programs from scratch -- Every expert programmer started exactly where you are now! +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -### Real-World Applications +### Success Criteria -This concept is used in: -1. Professional software development -2. Web applications and mobile apps -3. Data analysis and scientific computing -4. Automation and scripting -5. Game development +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -**Excellent work! You've mastered a fundamental concept!** - -*Ready for the next challenge? Keep going!* +**Great job! You've completed this lesson!** diff --git a/lessons/r/stage-1/level-2/lesson.md b/lessons/r/stage-1/level-2/lesson.md index c3742a5..5c73bcf 100644 --- a/lessons/r/stage-1/level-2/lesson.md +++ b/lessons/r/stage-1/level-2/lesson.md @@ -23,7 +23,7 @@ Learn how to store and work with different types of data in R. **Copy the following code EXACTLY as shown below into `main.R`** -```r +``` # Numeric variables age <- 25 score <- 100 @@ -43,12 +43,12 @@ cat(sprintf("Price: $%.2f\n", price)) ### How to Run **Method 1 (Vim - Recommended):** -```r +``` r ``` **Method 2 (Terminal):** -```bash +``` Rscript main.R ``` @@ -104,44 +104,35 @@ You just created a real R program! Here's what makes it work: --- -## ANSWER KEY (No peeking until you've tried!) +## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -The code you copied demonstrates fundamental R concepts: - -**Key Components:** -- Syntax rules specific to R -- How data is stored and manipulated -- Input/output operations -- Program flow and structure +``` +# Numeric variables +age <- 25 +score <- 100 +price <- 29.99 -### Common Errors & Solutions +# Character variable +name <- "Alex" -| Error | Cause | Solution | -|-------|-------|----------| -| Syntax error | Typo in code | Double-check spelling and punctuation | -| Runtime error | Code runs but crashes | Check your logic and data types | -| Unexpected output | Logic error | Review your algorithm step-by-step | +# Display +cat("Name:", name, "\n") +cat("Age:", age, "\n") +cat(sprintf("Price: $%.2f\n", price)) +``` -### Bonus Knowledge +### Explanation -- R has a rich ecosystem of libraries and tools -- Understanding these basics prepares you for advanced topics -- Practice is key - try writing similar programs from scratch -- Every expert programmer started exactly where you are now! +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -### Real-World Applications +### Success Criteria -This concept is used in: -1. Professional software development -2. Web applications and mobile apps -3. Data analysis and scientific computing -4. Automation and scripting -5. Game development +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -**Excellent work! You've mastered a fundamental concept!** - -*Ready for the next challenge? Keep going!* +**Great job! You've completed this lesson!** diff --git a/lessons/r/stage-1/level-3/lesson.md b/lessons/r/stage-1/level-3/lesson.md index 26d8435..925c24d 100644 --- a/lessons/r/stage-1/level-3/lesson.md +++ b/lessons/r/stage-1/level-3/lesson.md @@ -23,7 +23,7 @@ Master arithmetic operations and use R as your powerful calculator. **Copy the following code EXACTLY as shown below into `main.R`** -```r +``` a <- 10 b <- 3 @@ -40,12 +40,12 @@ cat("Modulus:", a %% b, "\n") ### How to Run **Method 1 (Vim - Recommended):** -```r +``` r ``` **Method 2 (Terminal):** -```bash +``` Rscript main.R ``` @@ -102,44 +102,32 @@ You just created a real R program! Here's what makes it work: --- -## ANSWER KEY (No peeking until you've tried!) - -### Code Breakdown +## ANSWER KEY (No cheating until you've tried!) -The code you copied demonstrates fundamental R concepts: +### Solution -**Key Components:** -- Syntax rules specific to R -- How data is stored and manipulated -- Input/output operations -- Program flow and structure - -### Common Errors & Solutions +``` +a <- 10 +b <- 3 -| Error | Cause | Solution | -|-------|-------|----------| -| Syntax error | Typo in code | Double-check spelling and punctuation | -| Runtime error | Code runs but crashes | Check your logic and data types | -| Unexpected output | Logic error | Review your algorithm step-by-step | +cat("Addition:", a + b, "\n") +cat("Subtraction:", a - b, "\n") +cat("Multiplication:", a * b, "\n") +cat("Division:", a / b, "\n") +cat("Integer division:", a %/% b, "\n") +cat("Modulus:", a %% b, "\n") +``` -### Bonus Knowledge +### Explanation -- R has a rich ecosystem of libraries and tools -- Understanding these basics prepares you for advanced topics -- Practice is key - try writing similar programs from scratch -- Every expert programmer started exactly where you are now! +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -### Real-World Applications +### Success Criteria -This concept is used in: -1. Professional software development -2. Web applications and mobile apps -3. Data analysis and scientific computing -4. Automation and scripting -5. Game development +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -**Excellent work! You've mastered a fundamental concept!** - -*Ready for the next challenge? Keep going!* +**Great job! You've completed this lesson!** diff --git a/lessons/r/stage-1/level-4/lesson.md b/lessons/r/stage-1/level-4/lesson.md index 464d9f6..6ed8025 100644 --- a/lessons/r/stage-1/level-4/lesson.md +++ b/lessons/r/stage-1/level-4/lesson.md @@ -23,7 +23,7 @@ Make your programs interactive by reading input from users. **Copy the following code EXACTLY as shown below into `main.R`** -```r +``` cat("Enter your name: ") name <- readLines("stdin", n=1) @@ -39,12 +39,12 @@ cat("You are", age, "years old.\n") ### How to Run **Method 1 (Vim - Recommended):** -```r +``` r ``` **Method 2 (Terminal):** -```bash +``` Rscript main.R ``` @@ -98,44 +98,31 @@ You just created a real R program! Here's what makes it work: --- -## ANSWER KEY (No peeking until you've tried!) - -### Code Breakdown +## ANSWER KEY (No cheating until you've tried!) -The code you copied demonstrates fundamental R concepts: +### Solution -**Key Components:** -- Syntax rules specific to R -- How data is stored and manipulated -- Input/output operations -- Program flow and structure +``` +cat("Enter your name: ") +name <- readLines("stdin", n=1) -### Common Errors & Solutions +cat("Enter your age: ") +age <- as.integer(readLines("stdin", n=1)) -| Error | Cause | Solution | -|-------|-------|----------| -| Syntax error | Typo in code | Double-check spelling and punctuation | -| Runtime error | Code runs but crashes | Check your logic and data types | -| Unexpected output | Logic error | Review your algorithm step-by-step | +cat("Hello,", name, "!\n") +cat("You are", age, "years old.\n") +``` -### Bonus Knowledge +### Explanation -- R has a rich ecosystem of libraries and tools -- Understanding these basics prepares you for advanced topics -- Practice is key - try writing similar programs from scratch -- Every expert programmer started exactly where you are now! +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -### Real-World Applications +### Success Criteria -This concept is used in: -1. Professional software development -2. Web applications and mobile apps -3. Data analysis and scientific computing -4. Automation and scripting -5. Game development +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -**Excellent work! You've mastered a fundamental concept!** - -*Ready for the next challenge? Keep going!* +**Great job! You've completed this lesson!** diff --git a/lessons/r/stage-1/level-5/lesson.md b/lessons/r/stage-1/level-5/lesson.md index 01922cd..ccb3e6f 100644 --- a/lessons/r/stage-1/level-5/lesson.md +++ b/lessons/r/stage-1/level-5/lesson.md @@ -23,7 +23,7 @@ Add decision-making to your programs with if/else statements. **Copy the following code EXACTLY as shown below into `main.R`** -```r +``` cat("Enter your score (0-100): ") score <- as.integer(readLines("stdin", n=1)) @@ -45,12 +45,12 @@ if (score >= 90) { ### How to Run **Method 1 (Vim - Recommended):** -```r +``` r ``` **Method 2 (Terminal):** -```bash +``` Rscript main.R ``` @@ -104,44 +104,37 @@ You just created a real R program! Here's what makes it work: --- -## ANSWER KEY (No peeking until you've tried!) +## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -The code you copied demonstrates fundamental R concepts: - -**Key Components:** -- Syntax rules specific to R -- How data is stored and manipulated -- Input/output operations -- Program flow and structure - -### Common Errors & Solutions +``` +cat("Enter your score (0-100): ") +score <- as.integer(readLines("stdin", n=1)) -| Error | Cause | Solution | -|-------|-------|----------| -| Syntax error | Typo in code | Double-check spelling and punctuation | -| Runtime error | Code runs but crashes | Check your logic and data types | -| Unexpected output | Logic error | Review your algorithm step-by-step | +if (score >= 90) { + cat("Grade: A - Excellent!\n") +} else if (score >= 80) { + cat("Grade: B - Good job!\n") +} else if (score >= 70) { + cat("Grade: C - Passing\n") +} else if (score >= 60) { + cat("Grade: D - Needs improvement\n") +} else { + cat("Grade: F - Study harder!\n") +} +``` -### Bonus Knowledge +### Explanation -- R has a rich ecosystem of libraries and tools -- Understanding these basics prepares you for advanced topics -- Practice is key - try writing similar programs from scratch -- Every expert programmer started exactly where you are now! +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -### Real-World Applications +### Success Criteria -This concept is used in: -1. Professional software development -2. Web applications and mobile apps -3. Data analysis and scientific computing -4. Automation and scripting -5. Game development +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -**Excellent work! You've mastered a fundamental concept!** - -*Ready for the next challenge? Keep going!* +**Great job! You've completed this lesson!** diff --git a/lessons/r/stage-1/level-6/lesson.md b/lessons/r/stage-1/level-6/lesson.md index f8e5970..de9dffa 100644 --- a/lessons/r/stage-1/level-6/lesson.md +++ b/lessons/r/stage-1/level-6/lesson.md @@ -23,7 +23,7 @@ Learn to repeat actions efficiently using loops. **Copy the following code EXACTLY as shown below into `main.R`** -```r +``` # For loop cat("Counting 1 to 10:\n") for (i in 1:10) { @@ -53,12 +53,12 @@ for (i in 1:10) { ### How to Run **Method 1 (Vim - Recommended):** -```r +``` r ``` **Method 2 (Terminal):** -```bash +``` Rscript main.R ``` @@ -112,44 +112,45 @@ You just created a real R program! Here's what makes it work: --- -## ANSWER KEY (No peeking until you've tried!) - -### Code Breakdown +## ANSWER KEY (No cheating until you've tried!) -The code you copied demonstrates fundamental R concepts: +### Solution -**Key Components:** -- Syntax rules specific to R -- How data is stored and manipulated -- Input/output operations -- Program flow and structure +``` +# For loop +cat("Counting 1 to 10:\n") +for (i in 1:10) { + cat(i, " ") +} +cat("\n") -### Common Errors & Solutions +# While loop +cat("\nCountdown:\n") +count <- 5 +while (count > 0) { + cat(count, "\n") + count <- count - 1 +} +cat("Blastoff!\n") -| Error | Cause | Solution | -|-------|-------|----------| -| Syntax error | Typo in code | Double-check spelling and punctuation | -| Runtime error | Code runs but crashes | Check your logic and data types | -| Unexpected output | Logic error | Review your algorithm step-by-step | +# Multiplication table +num <- 7 +cat("\n", num, " times table:\n", sep="") +for (i in 1:10) { + cat(num, "×", i, "=", num * i, "\n") +} +``` -### Bonus Knowledge +### Explanation -- R has a rich ecosystem of libraries and tools -- Understanding these basics prepares you for advanced topics -- Practice is key - try writing similar programs from scratch -- Every expert programmer started exactly where you are now! +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -### Real-World Applications +### Success Criteria -This concept is used in: -1. Professional software development -2. Web applications and mobile apps -3. Data analysis and scientific computing -4. Automation and scripting -5. Game development +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -**Excellent work! You've mastered a fundamental concept!** - -*Ready for the next challenge? Keep going!* +**Great job! You've completed this lesson!** diff --git a/lessons/r/stage-1/level-7/lesson.md b/lessons/r/stage-1/level-7/lesson.md index 5d21939..f3d04df 100644 --- a/lessons/r/stage-1/level-7/lesson.md +++ b/lessons/r/stage-1/level-7/lesson.md @@ -23,7 +23,7 @@ Organize your code into reusable functions/methods. **Copy the following code EXACTLY as shown below into `main.R`** -```r +``` # Function to greet someone greet <- function(name) { cat("Hello,", name, "!\n") @@ -57,12 +57,12 @@ cat("5! =", factorial_calc(5), "\n") ### How to Run **Method 1 (Vim - Recommended):** -```r +``` r ``` **Method 2 (Terminal):** -```bash +``` Rscript main.R ``` @@ -116,44 +116,49 @@ You just created a real R program! Here's what makes it work: --- -## ANSWER KEY (No peeking until you've tried!) +## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -The code you copied demonstrates fundamental R concepts: +``` +# Function to greet someone +greet <- function(name) { + cat("Hello,", name, "!\n") +} -**Key Components:** -- Syntax rules specific to R -- How data is stored and manipulated -- Input/output operations -- Program flow and structure +# Function that returns a value +add <- function(a, b) { + return(a + b) +} -### Common Errors & Solutions +# Function to calculate factorial +factorial_calc <- function(n) { + result <- 1 + for (i in 1:n) { + result <- result * i + } + return(result) +} + +greet("Alice") +greet("Bob") -| Error | Cause | Solution | -|-------|-------|----------| -| Syntax error | Typo in code | Double-check spelling and punctuation | -| Runtime error | Code runs but crashes | Check your logic and data types | -| Unexpected output | Logic error | Review your algorithm step-by-step | +sum_result <- add(5, 3) +cat("5 + 3 =", sum_result, "\n") -### Bonus Knowledge +cat("5! =", factorial_calc(5), "\n") +``` -- R has a rich ecosystem of libraries and tools -- Understanding these basics prepares you for advanced topics -- Practice is key - try writing similar programs from scratch -- Every expert programmer started exactly where you are now! +### Explanation -### Real-World Applications +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -This concept is used in: -1. Professional software development -2. Web applications and mobile apps -3. Data analysis and scientific computing -4. Automation and scripting -5. Game development +### Success Criteria ---- +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does -**Excellent work! You've mastered a fundamental concept!** +--- -*Ready for the next challenge? Keep going!* +**Great job! You've completed this lesson!** diff --git a/lessons/r/stage-2/level-1/lesson.md b/lessons/r/stage-2/level-1/lesson.md index 026ab22..ca9343a 100644 --- a/lessons/r/stage-2/level-1/lesson.md +++ b/lessons/r/stage-2/level-1/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in R:** -```r +``` ALGORITHM: Basic Algorithm Translation BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` Rscript hello.R ``` @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in R: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```r +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/r/stage-2/level-2/lesson.md b/lessons/r/stage-2/level-2/lesson.md index a2bf779..e502bb5 100644 --- a/lessons/r/stage-2/level-2/lesson.md +++ b/lessons/r/stage-2/level-2/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in R:** -```r +``` ALGORITHM: Variables in Algorithms BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` Rscript hello.R ``` @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in R: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```r +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/r/stage-2/level-3/lesson.md b/lessons/r/stage-2/level-3/lesson.md index dbf1421..1dd1522 100644 --- a/lessons/r/stage-2/level-3/lesson.md +++ b/lessons/r/stage-2/level-3/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in R:** -```r +``` ALGORITHM: Mathematical Algorithms BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` Rscript hello.R ``` @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in R: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```r +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/r/stage-2/level-4/lesson.md b/lessons/r/stage-2/level-4/lesson.md index 96fc750..1ffaa62 100644 --- a/lessons/r/stage-2/level-4/lesson.md +++ b/lessons/r/stage-2/level-4/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in R:** -```r +``` ALGORITHM: Input/Output Algorithms BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` Rscript hello.R ``` @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in R: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```r +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/r/stage-2/level-5/lesson.md b/lessons/r/stage-2/level-5/lesson.md index e6e1d76..2b19590 100644 --- a/lessons/r/stage-2/level-5/lesson.md +++ b/lessons/r/stage-2/level-5/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in R:** -```r +``` ALGORITHM: Decision Algorithms BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` Rscript hello.R ``` @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in R: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```r +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/r/stage-2/level-6/lesson.md b/lessons/r/stage-2/level-6/lesson.md index 47a027b..b29d309 100644 --- a/lessons/r/stage-2/level-6/lesson.md +++ b/lessons/r/stage-2/level-6/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in R:** -```r +``` ALGORITHM: Loop Algorithms BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` Rscript hello.R ``` @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in R: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```r +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/r/stage-2/level-7/lesson.md b/lessons/r/stage-2/level-7/lesson.md index eb228df..e245b43 100644 --- a/lessons/r/stage-2/level-7/lesson.md +++ b/lessons/r/stage-2/level-7/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in R:** -```r +``` ALGORITHM: Function Design BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` Rscript hello.R ``` @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in R: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```r +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/r/stage-3/level-1/lesson.md b/lessons/r/stage-3/level-1/lesson.md index a55eb85..601da5e 100644 --- a/lessons/r/stage-3/level-1/lesson.md +++ b/lessons/r/stage-3/level-1/lesson.md @@ -51,7 +51,7 @@ Simple Problem Analysis - Design an algorithm to solve this problem, then implem ### How to Run 1. **Run the code**: - ```bash + ``` Rscript hello.R ``` @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```r +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/r/stage-3/level-2/lesson.md b/lessons/r/stage-3/level-2/lesson.md index 119930b..2a3b886 100644 --- a/lessons/r/stage-3/level-2/lesson.md +++ b/lessons/r/stage-3/level-2/lesson.md @@ -51,7 +51,7 @@ Data Structure Planning - Design an algorithm to solve this problem, then implem ### How to Run 1. **Run the code**: - ```bash + ``` Rscript hello.R ``` @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```r +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/r/stage-3/level-3/lesson.md b/lessons/r/stage-3/level-3/lesson.md index ad7bdf8..078d519 100644 --- a/lessons/r/stage-3/level-3/lesson.md +++ b/lessons/r/stage-3/level-3/lesson.md @@ -51,7 +51,7 @@ Mathematical Problems - Design an algorithm to solve this problem, then implemen ### How to Run 1. **Run the code**: - ```bash + ``` Rscript hello.R ``` @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```r +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/r/stage-3/level-4/lesson.md b/lessons/r/stage-3/level-4/lesson.md index d2abdd9..6960876 100644 --- a/lessons/r/stage-3/level-4/lesson.md +++ b/lessons/r/stage-3/level-4/lesson.md @@ -51,7 +51,7 @@ Text Processing Problems - Design an algorithm to solve this problem, then imple ### How to Run 1. **Run the code**: - ```bash + ``` Rscript hello.R ``` @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```r +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/r/stage-3/level-5/lesson.md b/lessons/r/stage-3/level-5/lesson.md index 52c9aae..c1409ff 100644 --- a/lessons/r/stage-3/level-5/lesson.md +++ b/lessons/r/stage-3/level-5/lesson.md @@ -51,7 +51,7 @@ Logic Problems - Design an algorithm to solve this problem, then implement it. ### How to Run 1. **Run the code**: - ```bash + ``` Rscript hello.R ``` @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```r +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/r/stage-3/level-6/lesson.md b/lessons/r/stage-3/level-6/lesson.md index 94f90c5..3393e19 100644 --- a/lessons/r/stage-3/level-6/lesson.md +++ b/lessons/r/stage-3/level-6/lesson.md @@ -51,7 +51,7 @@ Search Algorithms - Design an algorithm to solve this problem, then implement it ### How to Run 1. **Run the code**: - ```bash + ``` Rscript hello.R ``` @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```r +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/r/stage-3/level-7/lesson.md b/lessons/r/stage-3/level-7/lesson.md index 222bb8d..6bcdeb3 100644 --- a/lessons/r/stage-3/level-7/lesson.md +++ b/lessons/r/stage-3/level-7/lesson.md @@ -51,7 +51,7 @@ Sorting Algorithms - Design an algorithm to solve this problem, then implement i ### How to Run 1. **Run the code**: - ```bash + ``` Rscript hello.R ``` @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```r +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/r/stage-4/level-1/lesson.md b/lessons/r/stage-4/level-1/lesson.md index 976c081..218a68a 100644 --- a/lessons/r/stage-4/level-1/lesson.md +++ b/lessons/r/stage-4/level-1/lesson.md @@ -51,7 +51,7 @@ Build a complete Calculator Application application that: ### How to Run 1. **Run the code**: - ```bash + ``` Rscript hello.R ``` @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```r +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/r/stage-4/level-2/lesson.md b/lessons/r/stage-4/level-2/lesson.md index 89422ba..12fa514 100644 --- a/lessons/r/stage-4/level-2/lesson.md +++ b/lessons/r/stage-4/level-2/lesson.md @@ -51,7 +51,7 @@ Build a complete Text Analysis Tool application that: ### How to Run 1. **Run the code**: - ```bash + ``` Rscript hello.R ``` @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```r +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/r/stage-4/level-3/lesson.md b/lessons/r/stage-4/level-3/lesson.md index 364f9d1..97f2b93 100644 --- a/lessons/r/stage-4/level-3/lesson.md +++ b/lessons/r/stage-4/level-3/lesson.md @@ -51,7 +51,7 @@ Build a complete Data Processing application that: ### How to Run 1. **Run the code**: - ```bash + ``` Rscript hello.R ``` @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```r +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/r/stage-4/level-4/lesson.md b/lessons/r/stage-4/level-4/lesson.md index a5bf3f8..b9c89ed 100644 --- a/lessons/r/stage-4/level-4/lesson.md +++ b/lessons/r/stage-4/level-4/lesson.md @@ -51,7 +51,7 @@ Build a complete File Operations application that: ### How to Run 1. **Run the code**: - ```bash + ``` Rscript hello.R ``` @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```r +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/r/stage-4/level-5/lesson.md b/lessons/r/stage-4/level-5/lesson.md index f42bd4c..176c421 100644 --- a/lessons/r/stage-4/level-5/lesson.md +++ b/lessons/r/stage-4/level-5/lesson.md @@ -51,7 +51,7 @@ Build a complete API Integration application that: ### How to Run 1. **Run the code**: - ```bash + ``` Rscript hello.R ``` @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```r +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/r/stage-4/level-6/lesson.md b/lessons/r/stage-4/level-6/lesson.md index c302fd7..e8d118a 100644 --- a/lessons/r/stage-4/level-6/lesson.md +++ b/lessons/r/stage-4/level-6/lesson.md @@ -51,7 +51,7 @@ Build a complete Database Operations application that: ### How to Run 1. **Run the code**: - ```bash + ``` Rscript hello.R ``` @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```r +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/r/stage-4/level-7/lesson.md b/lessons/r/stage-4/level-7/lesson.md index eb83f3b..5e045f5 100644 --- a/lessons/r/stage-4/level-7/lesson.md +++ b/lessons/r/stage-4/level-7/lesson.md @@ -51,7 +51,7 @@ Build a complete Complete Application application that: ### How to Run 1. **Run the code**: - ```bash + ``` Rscript hello.R ``` @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```r +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/r/stage-5/level-1/lesson.md b/lessons/r/stage-5/level-1/lesson.md index 7278469..1d67453 100644 --- a/lessons/r/stage-5/level-1/lesson.md +++ b/lessons/r/stage-5/level-1/lesson.md @@ -242,7 +242,7 @@ Follow these stages: **Your architecture will depend on your chosen project, but should include:** -```r +``` // Main program structure // - Data definitions // - Core functions diff --git a/lessons/r/stage-5/level-2/lesson.md b/lessons/r/stage-5/level-2/lesson.md index 001f4b9..541841a 100644 --- a/lessons/r/stage-5/level-2/lesson.md +++ b/lessons/r/stage-5/level-2/lesson.md @@ -233,7 +233,7 @@ Follow these stages: **Your architecture will depend on your chosen project, but should include:** -```r +``` // Main program structure // - Data definitions // - Core functions diff --git a/lessons/r/stage-5/level-3/lesson.md b/lessons/r/stage-5/level-3/lesson.md index 40adaf2..ca63bb7 100644 --- a/lessons/r/stage-5/level-3/lesson.md +++ b/lessons/r/stage-5/level-3/lesson.md @@ -238,7 +238,7 @@ Follow these stages: **Your architecture will depend on your chosen project, but should include:** -```r +``` // Main program structure // - Data definitions // - Core functions diff --git a/lessons/r/stage-5/level-4/lesson.md b/lessons/r/stage-5/level-4/lesson.md index d6d826a..c758409 100644 --- a/lessons/r/stage-5/level-4/lesson.md +++ b/lessons/r/stage-5/level-4/lesson.md @@ -233,7 +233,7 @@ Follow these stages: **Your architecture will depend on your chosen project, but should include:** -```r +``` // Main program structure // - Data definitions // - Core functions diff --git a/lessons/r/stage-5/level-5/lesson.md b/lessons/r/stage-5/level-5/lesson.md index 574c5a4..3ab8702 100644 --- a/lessons/r/stage-5/level-5/lesson.md +++ b/lessons/r/stage-5/level-5/lesson.md @@ -238,7 +238,7 @@ Follow these stages: **Your architecture will depend on your chosen project, but should include:** -```r +``` // Main program structure // - Data definitions // - Core functions diff --git a/lessons/r/stage-5/level-6/lesson.md b/lessons/r/stage-5/level-6/lesson.md index 962c9d9..9468fa7 100644 --- a/lessons/r/stage-5/level-6/lesson.md +++ b/lessons/r/stage-5/level-6/lesson.md @@ -232,7 +232,7 @@ Follow these stages: **Your architecture will depend on your chosen project, but should include:** -```r +``` // Main program structure // - Data definitions // - Core functions diff --git a/lessons/r/stage-5/level-7/lesson.md b/lessons/r/stage-5/level-7/lesson.md index 560efe2..4ac51e2 100644 --- a/lessons/r/stage-5/level-7/lesson.md +++ b/lessons/r/stage-5/level-7/lesson.md @@ -235,7 +235,7 @@ Follow these stages: **Your architecture will depend on your chosen project, but should include:** -```r +``` // Main program structure // - Data definitions // - Core functions diff --git a/lessons/rust/stage-1/level-1/lesson.md b/lessons/rust/stage-1/level-1/lesson.md index 7b64454..3b9e9e0 100644 --- a/lessons/rust/stage-1/level-1/lesson.md +++ b/lessons/rust/stage-1/level-1/lesson.md @@ -24,11 +24,11 @@ Welcome to your first step into programming with Rust! Today, you'll learn how t **Copy the following code EXACTLY as shown below into a new file called `hello.rs`** -```rust +``` fn main() { println!("Hello, World!"); } -```rust +``` --- @@ -36,22 +36,22 @@ fn main() { 1. **Open your terminal** (or command prompt) 2. **Navigate to where you saved your file**: - ```bash + ``` cd /path/to/your/folder - ```rust + ``` 3. **Compile the code**: - ```bash + ``` rustc hello.rs -o hello - ```rust + ``` 4. **Run your program**: - ```bash + ``` ./hello - ```rust + ``` **Expected output:** -```rust +``` Hello, World! -```rust +``` --- @@ -100,25 +100,25 @@ Remember to check the `VIM_CHEATSHEET.md` in the root directory for basic Vim co ### Code Breakdown -```rust +``` fn main() { -```rust +``` - **`fn`** = Function keyword - declares a function - **`main`** = Function name - every Rust program starts here - **`()`** = Parameters (empty means no inputs needed) - **`{`** = Opening brace - start of function body -```rust +``` println!("Hello, World!"); -```rust +``` - **`println!`** = Print line macro - prints text followed by newline - **`!`** = Indicates this is a macro, not a function - **`"`** = String literal start/end - **`;`** = Statement terminator - EVERY statement must end with this! -```rust +``` } -```rust +``` - **`}`** = Closing brace - end of function body ### Compilation Process @@ -147,7 +147,7 @@ fn main() { --- - **Congratulations! You've written your first Rust program!** + **Congratulations! You've written your first Rust program!** *Keep moving forward - next up: Variables!* @@ -167,42 +167,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```rs -fn main() { - println!("Hello, World!"); -} - -```rs - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard rust conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/rust/stage-1/level-2/lesson.md b/lessons/rust/stage-1/level-2/lesson.md index faee87d..ca62636 100644 --- a/lessons/rust/stage-1/level-2/lesson.md +++ b/lessons/rust/stage-1/level-2/lesson.md @@ -24,52 +24,52 @@ Now that you know how to create and run a basic Rust program, let's learn about **Copy the following code EXACTLY as shown below into a new file called `variables.rs`** -```rust +``` fn main() { // Integer variable let x = 42; - + // Floating-point variable let pi = 3.14159; - + // String variable let greeting = "Hello, Rust!"; - + // Boolean variable let is_rust_fun = true; - + // Print the variables println!("x = {}", x); println!("pi = {}", pi); println!("greeting = {}", greeting); println!("is_rust_fun = {}", is_rust_fun); } -```rust +``` --- ### How to Run 1. **Navigate to your working directory**: - ```bash + ``` cd /path/to/your/folder - ```rust + ``` 2. **Compile the code**: - ```bash + ``` rustc variables.rs -o variables - ```rust + ``` 3. **Run your program**: - ```bash + ``` ./variables - ```rust + ``` **Expected output:** -```rust +``` x = 42 pi = 3.14159 greeting = Hello, Rust! is_rust_fun = true -```rust +``` --- @@ -120,44 +120,44 @@ Check the `VIM_CHEATSHEET.md` for editing commands! ### Code Breakdown -```rust +``` fn main() { -```rust +``` - Same as before - entry point of the program -```rust +``` // Integer variable let x = 42; -```rust +``` - **`let`** = Variable declaration keyword - **`x`** = Variable name (identifier) - **`42`** = Integer literal value - **`;`** = Statement end -```rust +``` // Floating-point variable let pi = 3.14159; -```rust +``` - **`pi`** = Variable name - **`3.14159`** = Floating-point literal (decimal number) -```rust +``` // String variable let greeting = "Hello, Rust!"; -```rust +``` - **`"Hello, Rust!"`** = String literal (text) - Strings are enclosed in double quotes -```rust +``` // Boolean variable let is_rust_fun = true; -```rust +``` - **`true`** = Boolean literal (true/false values) -```rust +``` // Print the variables println!("x = {}", x); -```rust +``` - **`{}`** = Placeholder for variable value - **`x`** = Variable to insert at placeholder @@ -187,7 +187,7 @@ fn main() { --- - **Great job! You now understand variables in Rust!** + **Great job! You now understand variables in Rust!** *Next: Basic Math Operations!* @@ -207,42 +207,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```rs -fn main() { - println!("Hello, World!"); -} - -```rs - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard rust conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/rust/stage-1/level-3/lesson.md b/lessons/rust/stage-1/level-3/lesson.md index d117b73..165185f 100644 --- a/lessons/rust/stage-1/level-3/lesson.md +++ b/lessons/rust/stage-1/level-3/lesson.md @@ -24,12 +24,12 @@ Time to do some math! Programming is all about calculations. You'll learn how to **Copy the following code EXACTLY as shown below into a new file called `math.rs`** -```rust +``` fn main() { // Integer variables let a = 15; let b = 4; - + // Basic arithmetic operations println!("a = {}", a); println!("b = {}", b); @@ -38,37 +38,37 @@ fn main() { println!("a * b = {}", a * b); // Multiplication println!("a / b = {}", a / b); // Integer division println!("a % b = {}", a % b); // Modulo (remainder) - + // Floating-point division let x = 15.0; let y = 4.0; println!("x / y = {}", x / y); // Float division - + // Order of operations let result = 2 + 3 * 4; // Multiplication before addition println!("2 + 3 * 4 = {}", result); } -```rust +``` --- ### How to Run 1. **Navigate to your working directory**: - ```bash + ``` cd /path/to/your/folder - ```rust + ``` 2. **Compile the code**: - ```bash + ``` rustc math.rs -o math - ```rust + ``` 3. **Run your program**: - ```bash + ``` ./math - ```rust + ``` **Expected output:** -```rust +``` a = 15 b = 4 a + b = 19 @@ -78,7 +78,7 @@ a / b = 3 a % b = 3 x / y = 3.75 2 + 3 * 4 = 14 -```rust +``` --- @@ -128,36 +128,36 @@ Check the `VIM_CHEATSHEET.md` for editing commands! ### Code Breakdown -```rust +``` let a = 15; let b = 4; -```rust +``` - Declare integer variables for calculations -```rust +``` println!("a + b = {}", a + b); -```rust +``` - **`+`** = Addition operator - Combines values of `a` and `b` -```rust +``` println!("a / b = {}", a / b); -```rust +``` - **Integer division**: `15 / 4 = 3` (no decimal) - Rust truncates toward zero -```rust +``` let x = 15.0; let y = 4.0; println!("x / y = {}", x / y); -```rust +``` - **Float division**: Keeps decimal precision - `15.0 / 4.0 = 3.75` -```rust +``` let result = 2 + 3 * 4; println!("2 + 3 * 4 = {}", result); -```rust +``` - **Operator precedence**: `*` before `+` - `3 * 4 = 12`, then `2 + 12 = 14` @@ -187,7 +187,7 @@ Check the `VIM_CHEATSHEET.md` for editing commands! --- - **Excellent! You can now do math in Rust!** + **Excellent! You can now do math in Rust!** *Next: User Input!* @@ -207,42 +207,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```rs -fn main() { - println!("Hello, World!"); -} - -```rs - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard rust conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/rust/stage-1/level-4/lesson.md b/lessons/rust/stage-1/level-4/lesson.md index dc6d33b..e6a2ea9 100644 --- a/lessons/rust/stage-1/level-4/lesson.md +++ b/lessons/rust/stage-1/level-4/lesson.md @@ -24,50 +24,50 @@ Programs become much more interesting when they can interact with users! You'll **Copy the following code EXACTLY as shown below into a new file called `input.rs`** -```rust +``` use std::io; fn main() { // Read a string input println!("What's your name?"); - + let mut name = String::new(); io::stdin().read_line(&mut name).expect("Failed to read line"); - + println!("Hello, {}!", name.trim()); - + // Read a number input println!("Enter your age:"); - + let mut age_str = String::new(); io::stdin().read_line(&mut age_str).expect("Failed to read line"); - + let age: i32 = age_str.trim().parse().expect("Please enter a valid number"); - + println!("You are {} years old!", age); println!("Next year you'll be {}!", age + 1); } -```rust +``` --- ### How to Run 1. **Navigate to your working directory**: - ```bash + ``` cd /path/to/your/folder - ```rust + ``` 2. **Compile the code**: - ```bash + ``` rustc input.rs -o input - ```rust + ``` 3. **Run your program**: - ```bash + ``` ./input - ```rust + ``` **Example interaction:** -```rust +``` What's your name? Alice Hello, Alice! @@ -75,7 +75,7 @@ Enter your age: 25 You are 25 years old! Next year you'll be 26! -```rust +``` --- @@ -125,36 +125,36 @@ Check the `VIM_CHEATSHEET.md` for editing commands! ### Code Breakdown -```rust +``` use std::io; -```rust +``` - **`use`** = Import statement - **`std::io`** = Standard library input/output module -```rust +``` let mut name = String::new(); -```rust +``` - **`mut`** = Mutable (can be changed) - **`String::new()`** = Create empty string - **Why mutable?** `read_line` modifies the string -```rust +``` io::stdin().read_line(&mut name).expect("Failed to read line"); -```rust +``` - **`io::stdin()`** = Get standard input handle - **`.read_line(&mut name)`** = Read line into `name` - **`&mut`** = Mutable reference - **`.expect(...)`** = Handle potential errors -```rust +``` println!("Hello, {}!", name.trim()); -```rust +``` - **`.trim()`** = Remove leading/trailing whitespace - **Needed because** `read_line` includes the newline character -```rust +``` let age: i32 = age_str.trim().parse().expect("Please enter a valid number"); -```rust +``` - **`age: i32`** = Type annotation (32-bit integer) - **`.parse()`** = Convert string to number - **`.expect(...)`** = Error message if parsing fails @@ -186,7 +186,7 @@ use std::io; --- - **Awesome! Your programs can now interact with users!** + **Awesome! Your programs can now interact with users!** *Next: Conditionals and Decision Making!* @@ -206,42 +206,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```rs -fn main() { - println!("Hello, World!"); -} - -```rs - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard rust conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/rust/stage-1/level-5/lesson.md b/lessons/rust/stage-1/level-5/lesson.md index 9918880..4566798 100644 --- a/lessons/rust/stage-1/level-5/lesson.md +++ b/lessons/rust/stage-1/level-5/lesson.md @@ -24,20 +24,20 @@ Programs need to make decisions! You'll learn how to use `if`, `else if`, and `e **Copy the following code EXACTLY as shown below into a new file called `conditionals.rs`** -```rust +``` fn main() { let number = 7; - + // Simple if-else if number > 0 { println!("The number {} is positive", number); } else { println!("The number {} is not positive", number); } - + // Multiple conditions with else if let temperature = 25; - + if temperature > 30 { println!("It's very hot! {}°C", temperature); } else if temperature > 20 { @@ -47,52 +47,52 @@ fn main() { } else { println!("It's cold! {}°C", temperature); } - + // Comparison operators let a = 10; let b = 20; - + if a == b { println!("a equals b"); } else if a != b { println!("a does not equal b"); } - + if a < b { println!("a is less than b"); } - + if a <= b { println!("a is less than or equal to b"); } } -```rust +``` --- ### How to Run 1. **Navigate to your working directory**: - ```bash + ``` cd /path/to/your/folder - ```rust + ``` 2. **Compile the code**: - ```bash + ``` rustc conditionals.rs -o conditionals - ```rust + ``` 3. **Run your program**: - ```bash + ``` ./conditionals - ```rust + ``` **Expected output:** -```rust +``` The number 7 is positive It's warm. 25°C a does not equal b a is less than b a is less than or equal to b -```rust +``` --- @@ -142,18 +142,18 @@ Check the `VIM_CHEATSHEET.md` for editing commands! ### Code Breakdown -```rust +``` if number > 0 { println!("The number {} is positive", number); } else { println!("The number {} is not positive", number); } -```rust +``` - **`if number > 0`** = Condition: is number greater than 0? - **`{ ... }`** = Code block executed if condition true - **`else`** = Executed if condition false -```rust +``` if temperature > 30 { println!("It's very hot! {}°C", temperature); } else if temperature > 20 { @@ -163,18 +163,18 @@ Check the `VIM_CHEATSHEET.md` for editing commands! } else { println!("It's cold! {}°C", temperature); } -```rust +``` - **Chain of conditions** checked in order - **First true condition** executes, others skipped - **else** catches any remaining cases -```rust +``` if a == b { println!("a equals b"); } else if a != b { println!("a does not equal b"); } -```rust +``` - **`==`** = Equality comparison - **`!=`** = Inequality comparison - Note: `=` is assignment, `==` is comparison @@ -207,7 +207,7 @@ Check the `VIM_CHEATSHEET.md` for editing commands! --- - **Excellent! Your programs can now make decisions!** + **Excellent! Your programs can now make decisions!** *Next: Loops and Repetition!* @@ -227,42 +227,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```rs -fn main() { - println!("Hello, World!"); -} - -```rs - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard rust conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/rust/stage-1/level-6/lesson.md b/lessons/rust/stage-1/level-6/lesson.md index 1c71f3e..2402880 100644 --- a/lessons/rust/stage-1/level-6/lesson.md +++ b/lessons/rust/stage-1/level-6/lesson.md @@ -24,14 +24,14 @@ Sometimes you need to repeat actions! You'll learn different types of loops in R **Copy the following code EXACTLY as shown below into a new file called `loops.rs`** -```rust +``` fn main() { // For loop - iterate over a range println!("For loop counting:"); for i in 1..=5 { println!("Count: {}", i); } - + // While loop - repeat while condition is true println!("\nWhile loop counting:"); let mut count = 1; @@ -39,7 +39,7 @@ fn main() { println!("Count: {}", count); count = count + 1; } - + // Loop with break - infinite loop that we break out of println!("\nLoop with break:"); let mut number = 1; @@ -50,7 +50,7 @@ fn main() { } number = number + 1; } - + // Loop with continue - skip even numbers println!("\nSkipping even numbers:"); for i in 1..=10 { @@ -60,27 +60,27 @@ fn main() { println!("Odd number: {}", i); } } -```rust +``` --- ### How to Run 1. **Navigate to your working directory**: - ```bash + ``` cd /path/to/your/folder - ```rust + ``` 2. **Compile the code**: - ```bash + ``` rustc loops.rs -o loops - ```rust + ``` 3. **Run your program**: - ```bash + ``` ./loops - ```rust + ``` **Expected output:** -```rust +``` For loop counting: Count: 1 Count: 2 @@ -106,7 +106,7 @@ Odd number: 3 Odd number: 5 Odd number: 7 Odd number: 9 -```rust +``` --- @@ -156,27 +156,27 @@ Check the `VIM_CHEATSHEET.md` for editing commands! ### Code Breakdown -```rust +``` for i in 1..=5 { println!("Count: {}", i); } -```rust +``` - **`for i in 1..=5`** = `i` takes values 1, 2, 3, 4, 5 - **`..=`** = Inclusive range (includes 5) - **`i`** = Loop variable, different each iteration -```rust +``` let mut count = 1; while count <= 5 { println!("Count: {}", count); count = count + 1; } -```rust +``` - **`mut count`** = Mutable variable for counting - **`while count <= 5`** = Continue while condition true - **`count = count + 1`** = Increment counter -```rust +``` loop { println!("Number: {}", number); if number >= 3 { @@ -184,19 +184,19 @@ Check the `VIM_CHEATSHEET.md` for editing commands! } number = number + 1; } -```rust +``` - **`loop`** = Infinite loop - **`break`** = Exit loop when condition met - **Must have break** or loop runs forever! -```rust +``` for i in 1..=10 { if i % 2 == 0 { continue; } println!("Odd number: {}", i); } -```rust +``` - **`continue`** = Skip rest of iteration, go to next - **Even numbers** skipped, only odds printed @@ -225,7 +225,7 @@ Check the `VIM_CHEATSHEET.md` for editing commands! --- - **Fantastic! You can now create repeating programs!** + **Fantastic! You can now create repeating programs!** *Next: Functions - Code Organization!* @@ -245,42 +245,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```rs -fn main() { - println!("Hello, World!"); -} - -```rs - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard rust conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/rust/stage-1/level-7/lesson.md b/lessons/rust/stage-1/level-7/lesson.md index 0d1dfe3..0c57d00 100644 --- a/lessons/rust/stage-1/level-7/lesson.md +++ b/lessons/rust/stage-1/level-7/lesson.md @@ -24,7 +24,7 @@ Functions let you organize code into reusable pieces! You'll learn how to define **Copy the following code EXACTLY as shown below into a new file called `functions.rs`** -```rust +``` // Function that takes a parameter but returns nothing fn greet(name: &str) { println!("Hello, {}!", name); @@ -44,44 +44,44 @@ fn main() { // Call functions greet("World"); greet("Rust"); - + let sum = add(5, 3); println!("5 + 3 = {}", sum); - + let area = calculate_area(10, 5); println!("Area of 10x5 rectangle = {}", area); - + // Functions can call other functions let total = add(calculate_area(2, 3), add(1, 2)); println!("Complex calculation: (2*3) + (1+2) = {}", total); } -```rust +``` --- ### How to Run 1. **Navigate to your working directory**: - ```bash + ``` cd /path/to/your/folder - ```rust + ``` 2. **Compile the code**: - ```bash + ``` rustc functions.rs -o functions - ```rust + ``` 3. **Run your program**: - ```bash + ``` ./functions - ```rust + ``` **Expected output:** -```rust +``` Hello, World! Hello, Rust! 5 + 3 = 8 Area of 10x5 rectangle = 50 Complex calculation: (2*3) + (1+2) = 11 -```rust +``` --- @@ -131,44 +131,44 @@ Check the `VIM_CHEATSHEET.md` for editing commands! ### Code Breakdown -```rust +``` fn greet(name: &str) { println!("Hello, {}!", name); } -```rust +``` - **`fn greet`** = Function declaration - **`(name: &str)`** = Parameter: `name` of type string slice - **`{ ... }`** = Function body - **No return type** = Returns `()` (unit type) -```rust +``` fn add(a: i32, b: i32) -> i32 { a + b } -```rust +``` - **`-> i32`** = Returns 32-bit integer - **Last expression** `a + b` is returned (no semicolon!) - **Parameters** `a` and `b` are both `i32` -```rust +``` fn calculate_area(length: i32, width: i32) -> i32 { length * width } -```rust +``` - **Same pattern** as `add` function - **Multiplication** instead of addition -```rust +``` let sum = add(5, 3); println!("5 + 3 = {}", sum); -```rust +``` - **Function call** `add(5, 3)` returns `8` - **Store result** in `sum` variable - **Print result** -```rust +``` let total = add(calculate_area(2, 3), add(1, 2)); -```rust +``` - **Nested calls**: Functions can call other functions - **Evaluation order**: Innermost calls first - **Result**: `add(6, 3)` → `add(6, 3)` → `9` @@ -200,7 +200,7 @@ fn calculate_area(length: i32, width: i32) -> i32 { --- - **Congratulations! You've completed Stage 1: Copying Code!** + **Congratulations! You've completed Stage 1: Copying Code!** *You've learned the fundamentals of Rust programming. Great job! Next stages will build on these concepts.* @@ -220,42 +220,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```rs -fn main() { - println!("Hello, World!"); -} - -```rs - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard rust conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/rust/stage-2/level-1/lesson.md b/lessons/rust/stage-2/level-1/lesson.md index e9f14da..2037fa3 100644 --- a/lessons/rust/stage-2/level-1/lesson.md +++ b/lessons/rust/stage-2/level-1/lesson.md @@ -28,27 +28,27 @@ Welcome to Stage 2! Now that you understand Rust syntax, you'll learn to transla ### How to Run 1. **Compile the code**: - ```bash + ``` rustc hello.rs -o hello hello.rs - ```rust + ``` 2. **Run your program**: - ```bash + ``` ./hello hello - ```rust + ``` **Expected output:** -```rust +``` Hello, World! -```rust +``` ### Pseudocode: -```rust +``` START PROGRAM DISPLAY "Welcome to Rust programming!" DISPLAY "This is your first pseudocode translation!" END PROGRAM -```rust +``` **Your task:** Create a Rust program that does exactly what the pseudocode describes. @@ -57,25 +57,25 @@ END PROGRAM ### How to Create Your Solution 1. **Navigate to your working directory**: - ```bash + ``` cd /path/to/your/folder - ```rust + ``` 2. **Create your code file**: - ```bash + ``` touch basic_translation.rs - ```rust + ``` 3. **Write the Rust code** that matches the pseudocode 4. **Compile and test**: - ```bash + ``` rustc basic_translation.rs -o basic_translation ./basic_translation - ```rust + ``` **Expected output:** -```rust +``` Welcome to Rust programming! This is your first pseudocode translation! -```rust +``` --- @@ -123,20 +123,20 @@ Check the `VIM_CHEATSHEET.md` for editing commands! ### Step-by-Step Translation **Pseudocode:** -```rust +``` START PROGRAM DISPLAY "Welcome to Rust programming!" DISPLAY "This is your first pseudocode translation!" END PROGRAM -```rust +``` **Rust Code:** -```rust +``` fn main() { println!("Welcome to Rust programming!"); println!("This is your first pseudocode translation!"); } -```rust +``` ### Translation Guide @@ -164,7 +164,7 @@ fn main() { --- - **Great job! You've translated your first pseudocode!** + **Great job! You've translated your first pseudocode!** *Next: Variables in Pseudocode!* @@ -184,42 +184,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```rs -fn main() { - println!("Hello, World!"); -} - -```rs - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard rust conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/rust/stage-2/level-2/lesson.md b/lessons/rust/stage-2/level-2/lesson.md index 7c256c4..dda44d8 100644 --- a/lessons/rust/stage-2/level-2/lesson.md +++ b/lessons/rust/stage-2/level-2/lesson.md @@ -28,37 +28,37 @@ Variables are essential for storing and manipulating data. In this lesson, you'l ### How to Run 1. **Compile the code**: - ```bash + ``` rustc hello.rs -o hello hello.rs - ```rust + ``` 2. **Run your program**: - ```bash + ``` ./hello hello - ```rust + ``` **Expected output:** -```rust +``` Hello, World! -```rust +``` ### Pseudocode: -```rust +``` START PROGRAM DECLARE name AS TEXT SET name TO "Alice" - + DECLARE age AS NUMBER SET age TO 25 - + DECLARE is_student AS BOOLEAN SET is_student TO TRUE - + DISPLAY "Name: " + name DISPLAY "Age: " + age DISPLAY "Is student: " + is_student END PROGRAM -```rust +``` **Your task:** Create a Rust program that implements this pseudocode exactly. @@ -67,26 +67,26 @@ END PROGRAM ### How to Create Your Solution 1. **Navigate to your working directory**: - ```bash + ``` cd /path/to/your/folder - ```rust + ``` 2. **Create your code file**: - ```bash + ``` touch variables_translation.rs - ```rust + ``` 3. **Write the Rust code** that matches the pseudocode 4. **Compile and test**: - ```bash + ``` rustc variables_translation.rs -o variables_translation ./variables_translation - ```rust + ``` **Expected output:** -```rust +``` Name: Alice Age: 25 Is student: true -```rust +``` --- @@ -136,35 +136,35 @@ Check the `VIM_CHEATSHEET.md` for editing commands! ### Step-by-Step Translation **Pseudocode:** -```rust +``` START PROGRAM DECLARE name AS TEXT SET name TO "Alice" - + DECLARE age AS NUMBER SET age TO 25 - + DECLARE is_student AS BOOLEAN SET is_student TO TRUE - + DISPLAY "Name: " + name DISPLAY "Age: " + age DISPLAY "Is student: " + is_student END PROGRAM -```rust +``` **Rust Code:** -```rust +``` fn main() { let name = "Alice"; let age = 25; let is_student = true; - + println!("Name: {}", name); println!("Age: {}", age); println!("Is student: {}", is_student); } -```rust +``` ### Translation Guide @@ -194,7 +194,7 @@ fn main() { --- - **Excellent! You can now work with variables in pseudocode!** + **Excellent! You can now work with variables in pseudocode!** *Next: Mathematical Pseudocode!* @@ -214,42 +214,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```rs -fn main() { - println!("Hello, World!"); -} - -```rs - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard rust conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/rust/stage-2/level-3/lesson.md b/lessons/rust/stage-2/level-3/lesson.md index 89bd7c6..b95007b 100644 --- a/lessons/rust/stage-2/level-3/lesson.md +++ b/lessons/rust/stage-2/level-3/lesson.md @@ -28,53 +28,53 @@ Math is everywhere in programming! You'll translate pseudocode that performs cal ### How to Run 1. **Compile the code**: - ```bash + ``` rustc hello.rs -o hello hello.rs - ```rust + ``` 2. **Run your program**: - ```bash + ``` ./hello hello - ```rust + ``` **Expected output:** -```rust +``` Hello, World! -```rust +``` ### Pseudocode: -```rust +``` START PROGRAM DECLARE a AS NUMBER SET a TO 10 - + DECLARE b AS NUMBER SET b TO 3 - + DECLARE sum AS NUMBER SET sum TO a + b - + DECLARE difference AS NUMBER SET difference TO a - b - + DECLARE product AS NUMBER SET product TO a * b - + DECLARE quotient AS NUMBER SET quotient TO a / b - + DISPLAY "a = " + a DISPLAY "b = " + b DISPLAY "Sum: " + sum DISPLAY "Difference: " + difference DISPLAY "Product: " + product DISPLAY "Quotient: " + quotient - + DECLARE complex AS NUMBER SET complex TO (a + b) * 2 - quotient DISPLAY "Complex calculation: " + complex END PROGRAM -```rust +``` **Your task:** Create a Rust program that performs these mathematical operations. @@ -83,22 +83,22 @@ END PROGRAM ### How to Create Your Solution 1. **Navigate to your working directory**: - ```bash + ``` cd /path/to/your/folder - ```rust + ``` 2. **Create your code file**: - ```bash + ``` touch math_translation.rs - ```rust + ``` 3. **Write the Rust code** that matches the pseudocode 4. **Compile and test**: - ```bash + ``` rustc math_translation.rs -o math_translation ./math_translation - ```rust + ``` **Expected output:** -```rust +``` a = 10 b = 3 Sum: 13 @@ -106,7 +106,7 @@ Difference: 7 Product: 30 Quotient: 3 Complex calculation: 23 -```rust +``` --- @@ -156,61 +156,61 @@ Check the `VIM_CHEATSHEET.md` for editing commands! ### Step-by-Step Translation **Pseudocode:** -```rust +``` START PROGRAM DECLARE a AS NUMBER SET a TO 10 - + DECLARE b AS NUMBER SET b TO 3 - + DECLARE sum AS NUMBER SET sum TO a + b - + DECLARE difference AS NUMBER SET difference TO a - b - + DECLARE product AS NUMBER SET product TO a * b - + DECLARE quotient AS NUMBER SET quotient TO a / b - + DISPLAY "a = " + a DISPLAY "b = " + b DISPLAY "Sum: " + sum DISPLAY "Difference: " + difference DISPLAY "Product: " + product DISPLAY "Quotient: " + quotient - + DECLARE complex AS NUMBER SET complex TO (a + b) * 2 - quotient DISPLAY "Complex calculation: " + complex END PROGRAM -```rust +``` **Rust Code:** -```rust +``` fn main() { let a = 10; let b = 3; - + let sum = a + b; let difference = a - b; let product = a * b; let quotient = a / b; - + println!("a = {}", a); println!("b = {}", b); println!("Sum: {}", sum); println!("Difference: {}", difference); println!("Product: {}", product); println!("Quotient: {}", quotient); - + let complex = (a + b) * 2 - quotient; println!("Complex calculation: {}", complex); } -```rust +``` ### Translation Guide @@ -242,7 +242,7 @@ fn main() { --- - **Great! You can handle mathematical pseudocode!** + **Great! You can handle mathematical pseudocode!** *Next: Input/Output Pseudocode!* @@ -262,42 +262,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```rs -fn main() { - println!("Hello, World!"); -} - -```rs - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard rust conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/rust/stage-2/level-4/lesson.md b/lessons/rust/stage-2/level-4/lesson.md index 5b6feb3..3e05076 100644 --- a/lessons/rust/stage-2/level-4/lesson.md +++ b/lessons/rust/stage-2/level-4/lesson.md @@ -28,43 +28,43 @@ Programs become interactive when they can accept input and provide output! You'l ### How to Run 1. **Compile the code**: - ```bash + ``` rustc hello.rs -o hello hello.rs - ```rust + ``` 2. **Run your program**: - ```bash + ``` ./hello hello - ```rust + ``` **Expected output:** -```rust +``` Hello, World! -```rust +``` ### Pseudocode: -```rust +``` START PROGRAM DISPLAY "Welcome to the calculator!" - + DISPLAY "Enter first number:" READ first_number AS NUMBER - + DISPLAY "Enter second number:" READ second_number AS NUMBER - + DECLARE sum AS NUMBER SET sum TO first_number + second_number - + DECLARE product AS NUMBER SET product TO first_number * second_number - + DISPLAY "Numbers entered: " + first_number + " and " + second_number DISPLAY "Sum: " + sum DISPLAY "Product: " + product DISPLAY "Thank you for using the calculator!" END PROGRAM -```rust +``` **Your task:** Create an interactive Rust program that matches this pseudocode. @@ -73,22 +73,22 @@ END PROGRAM ### How to Create Your Solution 1. **Navigate to your working directory**: - ```bash + ``` cd /path/to/your/folder - ```rust + ``` 2. **Create your code file**: - ```bash + ``` touch io_translation.rs - ```rust + ``` 3. **Write the Rust code** that matches the pseudocode 4. **Compile and test**: - ```bash + ``` rustc io_translation.rs -o io_translation ./io_translation - ```rust + ``` **Example interaction:** -```rust +``` Welcome to the calculator! Enter first number: 5 @@ -98,7 +98,7 @@ Numbers entered: 5 and 3 Sum: 8 Product: 15 Thank you for using the calculator! -```rust +``` --- @@ -147,55 +147,55 @@ Check the `VIM_CHEATSHEET.md` for editing commands! ### Step-by-Step Translation **Pseudocode:** -```rust +``` START PROGRAM DISPLAY "Welcome to the calculator!" - + DISPLAY "Enter first number:" READ first_number AS NUMBER - + DISPLAY "Enter second number:" READ second_number AS NUMBER - + DECLARE sum AS NUMBER SET sum TO first_number + second_number - + DECLARE product AS NUMBER SET product TO first_number * second_number - + DISPLAY "Numbers entered: " + first_number + " and " + second_number DISPLAY "Sum: " + sum DISPLAY "Product: " + product DISPLAY "Thank you for using the calculator!" END PROGRAM -```rust +``` **Rust Code:** -```rust +``` use std::io; fn main() { println!("Welcome to the calculator!"); - + println!("Enter first number:"); let mut first_input = String::new(); io::stdin().read_line(&mut first_input).expect("Failed to read line"); let first_number: i32 = first_input.trim().parse().expect("Please enter a number"); - + println!("Enter second number:"); let mut second_input = String::new(); io::stdin().read_line(&mut second_input).expect("Failed to read line"); let second_number: i32 = second_input.trim().parse().expect("Please enter a number"); - + let sum = first_number + second_number; let product = first_number * second_number; - + println!("Numbers entered: {} and {}", first_number, second_number); println!("Sum: {}", sum); println!("Product: {}", product); println!("Thank you for using the calculator!"); } -```rust +``` ### Translation Guide @@ -224,7 +224,7 @@ fn main() { --- - **Awesome! You can handle interactive pseudocode!** + **Awesome! You can handle interactive pseudocode!** *Next: Decision Pseudocode!* @@ -244,42 +244,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```rs -fn main() { - println!("Hello, World!"); -} - -```rs - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard rust conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/rust/stage-2/level-5/lesson.md b/lessons/rust/stage-2/level-5/lesson.md index af61cc5..305cb9a 100644 --- a/lessons/rust/stage-2/level-5/lesson.md +++ b/lessons/rust/stage-2/level-5/lesson.md @@ -28,27 +28,27 @@ Programs make decisions! You'll translate pseudocode that uses conditional logic ### How to Run 1. **Compile the code**: - ```bash + ``` rustc hello.rs -o hello hello.rs - ```rust + ``` 2. **Run your program**: - ```bash + ``` ./hello hello - ```rust + ``` **Expected output:** -```rust +``` Hello, World! -```rust +``` ### Pseudocode: -```rust +``` START PROGRAM DISPLAY "Number Classifier" DISPLAY "Enter a number:" READ number AS NUMBER - + IF number > 0 THEN DISPLAY number + " is positive" ELSE IF number < 0 THEN @@ -56,13 +56,13 @@ START PROGRAM ELSE DISPLAY number + " is zero" END IF - + IF number % 2 == 0 THEN DISPLAY number + " is even" ELSE DISPLAY number + " is odd" END IF - + IF number >= 10 THEN DISPLAY "That's a big number!" ELSE IF number >= 0 THEN @@ -71,7 +71,7 @@ START PROGRAM DISPLAY "That's a negative number!" END IF END PROGRAM -```rust +``` **Your task:** Create a Rust program that classifies numbers based on the pseudocode logic. @@ -80,29 +80,29 @@ END PROGRAM ### How to Create Your Solution 1. **Navigate to your working directory**: - ```bash + ``` cd /path/to/your/folder - ```rust + ``` 2. **Create your code file**: - ```bash + ``` touch decision_translation.rs - ```rust + ``` 3. **Write the Rust code** that matches the pseudocode 4. **Compile and test**: - ```bash + ``` rustc decision_translation.rs -o decision_translation ./decision_translation - ```rust + ``` **Example interaction:** -```rust +``` Number Classifier Enter a number: 7 7 is positive 7 is odd That's a small number! -```rust +``` --- @@ -153,12 +153,12 @@ Check the `VIM_CHEATSHEET.md` for editing commands! ### Step-by-Step Translation **Pseudocode:** -```rust +``` START PROGRAM DISPLAY "Number Classifier" DISPLAY "Enter a number:" READ number AS NUMBER - + IF number > 0 THEN DISPLAY number + " is positive" ELSE IF number < 0 THEN @@ -166,13 +166,13 @@ START PROGRAM ELSE DISPLAY number + " is zero" END IF - + IF number % 2 == 0 THEN DISPLAY number + " is even" ELSE DISPLAY number + " is odd" END IF - + IF number >= 10 THEN DISPLAY "That's a big number!" ELSE IF number >= 0 THEN @@ -181,20 +181,20 @@ START PROGRAM DISPLAY "That's a negative number!" END IF END PROGRAM -```rust +``` **Rust Code:** -```rust +``` use std::io; fn main() { println!("Number Classifier"); println!("Enter a number:"); - + let mut input = String::new(); io::stdin().read_line(&mut input).expect("Failed to read line"); let number: i32 = input.trim().parse().expect("Please enter a number"); - + if number > 0 { println!("{} is positive", number); } else if number < 0 { @@ -202,13 +202,13 @@ fn main() { } else { println!("{} is zero", number); } - + if number % 2 == 0 { println!("{} is even", number); } else { println!("{} is odd", number); } - + if number >= 10 { println!("That's a big number!"); } else if number >= 0 { @@ -217,7 +217,7 @@ fn main() { println!("That's a negative number!"); } } -```rust +``` ### Translation Guide @@ -247,7 +247,7 @@ fn main() { --- - **Excellent! You can handle decision-making pseudocode!** + **Excellent! You can handle decision-making pseudocode!** *Next: Loop Pseudocode!* @@ -267,42 +267,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```rs -fn main() { - println!("Hello, World!"); -} - -```rs - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard rust conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/rust/stage-2/level-6/lesson.md b/lessons/rust/stage-2/level-6/lesson.md index a011a15..7c2d5b8 100644 --- a/lessons/rust/stage-2/level-6/lesson.md +++ b/lessons/rust/stage-2/level-6/lesson.md @@ -28,46 +28,46 @@ Repetition is powerful! You'll translate pseudocode that uses loops to repeat ac ### How to Run 1. **Compile the code**: - ```bash + ``` rustc hello.rs -o hello hello.rs - ```rust + ``` 2. **Run your program**: - ```bash + ``` ./hello hello - ```rust + ``` **Expected output:** -```rust +``` Hello, World! -```rust +``` ### Pseudocode: -```rust +``` START PROGRAM DISPLAY "Countdown Program" - + DECLARE counter AS NUMBER SET counter TO 5 - + WHILE counter > 0 DO DISPLAY "Count: " + counter SET counter TO counter - 1 END WHILE - + DISPLAY "Blast off!" - + DISPLAY "Even numbers from 1 to 10:" FOR i FROM 1 TO 10 DO IF i % 2 == 0 THEN DISPLAY i END IF END FOR - + DISPLAY "Loop with break:" DECLARE num AS NUMBER SET num TO 1 - + WHILE TRUE DO DISPLAY "Number: " + num IF num >= 4 THEN @@ -76,7 +76,7 @@ START PROGRAM SET num TO num + 1 END WHILE END PROGRAM -```rust +``` **Your task:** Create a Rust program that implements these looping constructs. @@ -85,22 +85,22 @@ END PROGRAM ### How to Create Your Solution 1. **Navigate to your working directory**: - ```bash + ``` cd /path/to/your/folder - ```rust + ``` 2. **Create your code file**: - ```bash + ``` touch loop_translation.rs - ```rust + ``` 3. **Write the Rust code** that matches the pseudocode 4. **Compile and test**: - ```bash + ``` rustc loop_translation.rs -o loop_translation ./loop_translation - ```rust + ``` **Expected output:** -```rust +``` Countdown Program Count: 5 Count: 4 @@ -119,7 +119,7 @@ Number: 1 Number: 2 Number: 3 Number: 4 -```rust +``` --- @@ -169,31 +169,31 @@ Check the `VIM_CHEATSHEET.md` for editing commands! ### Step-by-Step Translation **Pseudocode:** -```rust +``` START PROGRAM DISPLAY "Countdown Program" - + DECLARE counter AS NUMBER SET counter TO 5 - + WHILE counter > 0 DO DISPLAY "Count: " + counter SET counter TO counter - 1 END WHILE - + DISPLAY "Blast off!" - + DISPLAY "Even numbers from 1 to 10:" FOR i FROM 1 TO 10 DO IF i % 2 == 0 THEN DISPLAY i END IF END FOR - + DISPLAY "Loop with break:" DECLARE num AS NUMBER SET num TO 1 - + WHILE TRUE DO DISPLAY "Number: " + num IF num >= 4 THEN @@ -202,32 +202,32 @@ START PROGRAM SET num TO num + 1 END WHILE END PROGRAM -```rust +``` **Rust Code:** -```rust +``` fn main() { println!("Countdown Program"); - + let mut counter = 5; - + while counter > 0 { println!("Count: {}", counter); counter = counter - 1; } - + println!("Blast off!"); - + println!("Even numbers from 1 to 10:"); for i in 1..=10 { if i % 2 == 0 { println!("{}", i); } } - + println!("Loop with break:"); let mut num = 1; - + loop { println!("Number: {}", num); if num >= 4 { @@ -236,7 +236,7 @@ fn main() { num = num + 1; } } -```rust +``` ### Translation Guide @@ -267,7 +267,7 @@ fn main() { --- - **Fantastic! You can handle looping pseudocode!** + **Fantastic! You can handle looping pseudocode!** *Next: Function Pseudocode!* @@ -287,42 +287,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```rs -fn main() { - println!("Hello, World!"); -} - -```rs - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard rust conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/rust/stage-2/level-7/lesson.md b/lessons/rust/stage-2/level-7/lesson.md index 998641c..0ae454a 100644 --- a/lessons/rust/stage-2/level-7/lesson.md +++ b/lessons/rust/stage-2/level-7/lesson.md @@ -28,22 +28,22 @@ Functions organize code into reusable pieces! You'll translate pseudocode that d ### How to Run 1. **Compile the code**: - ```bash + ``` rustc hello.rs -o hello hello.rs - ```rust + ``` 2. **Run your program**: - ```bash + ``` ./hello hello - ```rust + ``` **Expected output:** -```rust +``` Hello, World! -```rust +``` ### Pseudocode: -```rust +``` FUNCTION greet(name) DISPLAY "Hello, " + name + "!" END FUNCTION @@ -63,23 +63,23 @@ END FUNCTION START PROGRAM CALL greet("World") CALL greet("Rust Programmer") - + DECLARE result AS NUMBER SET result TO CALL add_numbers(5, 3) DISPLAY "5 + 3 = " + result - + DECLARE num AS NUMBER SET num TO 7 - + IF CALL is_even(num) THEN DISPLAY num + " is even" ELSE DISPLAY num + " is odd" END IF - + DISPLAY "Program complete!" END PROGRAM -```rust +``` **Your task:** Create a Rust program with functions that match the pseudocode. @@ -88,28 +88,28 @@ END PROGRAM ### How to Create Your Solution 1. **Navigate to your working directory**: - ```bash + ``` cd /path/to/your/folder - ```rust + ``` 2. **Create your code file**: - ```bash + ``` touch function_translation.rs - ```rust + ``` 3. **Write the Rust code** that matches the pseudocode 4. **Compile and test**: - ```bash + ``` rustc function_translation.rs -o function_translation ./function_translation - ```rust + ``` **Expected output:** -```rust +``` Hello, World! Hello, Rust Programmer! 5 + 3 = 8 7 is odd Program complete! -```rust +``` --- @@ -160,7 +160,7 @@ Check the `VIM_CHEATSHEET.md` for editing commands! ### Step-by-Step Translation **Pseudocode:** -```rust +``` FUNCTION greet(name) DISPLAY "Hello, " + name + "!" END FUNCTION @@ -180,26 +180,26 @@ END FUNCTION START PROGRAM CALL greet("World") CALL greet("Rust Programmer") - + DECLARE result AS NUMBER SET result TO CALL add_numbers(5, 3) DISPLAY "5 + 3 = " + result - + DECLARE num AS NUMBER SET num TO 7 - + IF CALL is_even(num) THEN DISPLAY num + " is even" ELSE DISPLAY num + " is odd" END IF - + DISPLAY "Program complete!" END PROGRAM -```rust +``` **Rust Code:** -```rust +``` fn greet(name: &str) { println!("Hello, {}!", name); } @@ -219,21 +219,21 @@ fn is_even(number: i32) -> bool { fn main() { greet("World"); greet("Rust Programmer"); - + let result = add_numbers(5, 3); println!("5 + 3 = {}", result); - + let num = 7; - + if is_even(num) { println!("{} is even", num); } else { println!("{} is odd", num); } - + println!("Program complete!"); } -```rust +``` ### Translation Guide @@ -263,7 +263,7 @@ fn main() { --- - **Congratulations! You've completed Stage 2: Pseudocode to Code!** + **Congratulations! You've completed Stage 2: Pseudocode to Code!** *You've learned to translate written logic into working Rust programs. Excellent progress! Next stages will build on these skills.* @@ -283,42 +283,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```rs -fn main() { - println!("Hello, World!"); -} - -```rs - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard rust conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/rust/stage-3/level-1/lesson.md b/lessons/rust/stage-3/level-1/lesson.md index 3070912..7f641fa 100644 --- a/lessons/rust/stage-3/level-1/lesson.md +++ b/lessons/rust/stage-3/level-1/lesson.md @@ -28,19 +28,19 @@ Welcome to Stage 3! Now you'll learn to analyze problems and design solutions be ### How to Run 1. **Compile the code**: - ```bash + ``` rustc hello.rs -o hello hello.rs - ```rust + ``` 2. **Run your program**: - ```bash + ``` ./hello hello - ```rust + ``` **Expected output:** -```rust +``` Hello, World! -```rust +``` ### Problem: Temperature Converter @@ -57,27 +57,27 @@ You need to create a program that converts temperatures between Celsius and Fahr - Fahrenheit to Celsius: `C = (F - 32) × 5/9` **Example Interactions:** -```rust +``` What conversion do you want? 1. Celsius to Fahrenheit 2. Fahrenheit to Celsius Enter choice (1 or 2): 1 Enter temperature in Celsius: 25 25°C is equal to 77°F -```rust +``` --- ### How to Create Your Solution 1. **Navigate to your working directory**: - ```bash + ``` cd /path/to/your/folder - ```rust + ``` 2. **Create your pseudocode file**: - ```bash + ``` touch simple_analysis.md - ```rust + ``` 3. **Write pseudocode** that solves the problem step by step 4. **Think about edge cases** (what if user enters invalid choice?) @@ -142,16 +142,16 @@ Check the `VIM_CHEATSHEET.md` for editing commands! ### Sample Pseudocode Solution -```rust +``` START PROGRAM DISPLAY "Temperature Converter" DISPLAY "What conversion do you want?" DISPLAY "1. Celsius to Fahrenheit" DISPLAY "2. Fahrenheit to Celsius" DISPLAY "Enter choice (1 or 2):" - + READ choice AS NUMBER - + IF choice == 1 THEN DISPLAY "Enter temperature in Celsius:" READ celsius AS NUMBER @@ -166,7 +166,7 @@ START PROGRAM DISPLAY "Invalid choice. Please enter 1 or 2." END IF END PROGRAM -```rust +``` ### Analysis Breakdown @@ -199,7 +199,7 @@ END PROGRAM --- - **Great job! You analyzed your first programming problem!** + **Great job! You analyzed your first programming problem!** *Next: Data Management Problems!* @@ -219,42 +219,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```rs -fn main() { - println!("Hello, World!"); -} - -```rs - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard rust conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/rust/stage-3/level-2/lesson.md b/lessons/rust/stage-3/level-2/lesson.md index 5b419cf..cf5d468 100644 --- a/lessons/rust/stage-3/level-2/lesson.md +++ b/lessons/rust/stage-3/level-2/lesson.md @@ -28,19 +28,19 @@ Data management involves organizing, storing, and manipulating information. You' ### How to Run 1. **Compile the code**: - ```bash + ``` rustc hello.rs -o hello hello.rs - ```rust + ``` 2. **Run your program**: - ```bash + ``` ./hello hello - ```rust + ``` **Expected output:** -```rust +``` Hello, World! -```rust +``` ### Problem: Student Grade Calculator @@ -66,7 +66,7 @@ Create a program that helps teachers calculate final grades for students. The pr - Assignment 3: 35% **Example Interaction:** -```rust +``` Enter student name: Alice Johnson Enter Assignment 1 score (0-100): 85 Enter Assignment 2 score (0-100): 92 @@ -79,20 +79,20 @@ Assignment 2: 92/100 (35%) Assignment 3: 78/100 (35%) Final Average: 84.9% Letter Grade: B -```rust +``` --- ### How to Create Your Solution 1. **Navigate to your working directory**: - ```bash + ``` cd /path/to/your/folder - ```rust + ``` 2. **Create your pseudocode file**: - ```bash + ``` touch data_management.md - ```rust + ``` 3. **Think about data storage** - What variables do you need? 4. **Plan calculations** - How to compute weighted average? 5. **Design output** - How to present the information clearly? @@ -155,32 +155,32 @@ Check the `VIM_CHEATSHEET.md` for editing commands! ### Sample Pseudocode Solution -```rust +``` START PROGRAM DISPLAY "Student Grade Calculator" DISPLAY "Enter student name:" READ student_name AS TEXT - + DISPLAY "Enter Assignment 1 score (0-100):" READ score1 AS NUMBER - + DISPLAY "Enter Assignment 2 score (0-100):" READ score2 AS NUMBER - + DISPLAY "Enter Assignment 3 score (0-100):" READ score3 AS NUMBER - + // Calculate weighted average SET weight1 TO 0.30 SET weight2 TO 0.35 SET weight3 TO 0.35 - + SET weighted_score1 TO score1 * weight1 SET weighted_score2 TO score2 * weight2 SET weighted_score3 TO score3 * weight3 - + SET final_average TO weighted_score1 + weighted_score2 + weighted_score3 - + // Determine letter grade IF final_average >= 90 THEN SET letter_grade TO "A" @@ -193,7 +193,7 @@ START PROGRAM ELSE SET letter_grade TO "F" END IF - + // Display report DISPLAY "Student Report for " + student_name DISPLAY "--------------------------" @@ -203,7 +203,7 @@ START PROGRAM DISPLAY "Final Average: " + final_average + "%" DISPLAY "Letter Grade: " + letter_grade END PROGRAM -```rust +``` ### Analysis Breakdown @@ -242,7 +242,7 @@ END PROGRAM --- - **Excellent! You managed multiple data points effectively!** + **Excellent! You managed multiple data points effectively!** *Next: Mathematical Problems!* @@ -262,42 +262,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```rs -fn main() { - println!("Hello, World!"); -} - -```rs - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard rust conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/rust/stage-3/level-3/lesson.md b/lessons/rust/stage-3/level-3/lesson.md index db872d8..87de0de 100644 --- a/lessons/rust/stage-3/level-3/lesson.md +++ b/lessons/rust/stage-3/level-3/lesson.md @@ -28,19 +28,19 @@ Mathematical problems often require careful analysis of formulas and algorithms. ### How to Run 1. **Compile the code**: - ```bash + ``` rustc hello.rs -o hello hello.rs - ```rust + ``` 2. **Run your program**: - ```bash + ``` ./hello hello - ```rust + ``` **Expected output:** -```rust +``` Hello, World! -```rust +``` ### Problem: Compound Interest Calculator @@ -55,9 +55,9 @@ Create a program that calculates compound interest for savings accounts. The pro 6. Display a detailed breakdown **Compound Interest Formula:** -```rust +``` A = P(1 + r/n)^(nt) -```rust +``` Where: - A = Final amount - P = Principal amount @@ -71,7 +71,7 @@ Where: - Monthly: n = 12 **Example Interaction:** -```rust +``` Compound Interest Calculator Enter principal amount: $1000 Enter annual interest rate (%): 5 @@ -90,20 +90,20 @@ Years: 3 Compounding: Quarterly Final Amount: $1161.54 Total Interest: $161.54 -```rust +``` --- ### How to Create Your Solution 1. **Navigate to your working directory**: - ```bash + ``` cd /path/to/your/folder - ```rust + ``` 2. **Create your pseudocode file**: - ```bash + ``` touch mathematical_problems.md - ```rust + ``` 3. **Break down the formula** - Understand each component 4. **Plan input validation** - Ensure reasonable values 5. **Design calculations** - Step-by-step mathematical operations @@ -161,34 +161,34 @@ Check the `VIM_CHEATSHEET.md` for editing commands! - Final Amount (A): Result of compound interest formula **Formula Breakdown:** -```rust +``` A = P(1 + r/n)^(nt) Total Interest = A - P -```rust +``` ### Sample Pseudocode Solution -```rust +``` START PROGRAM DISPLAY "Compound Interest Calculator" - + DISPLAY "Enter principal amount:" READ principal AS NUMBER - + DISPLAY "Enter annual interest rate (%):" READ rate_percent AS NUMBER SET rate TO rate_percent / 100 // Convert to decimal - + DISPLAY "Enter number of years:" READ years AS NUMBER - + DISPLAY "Compounding frequency:" DISPLAY "1. Yearly" DISPLAY "2. Quarterly" DISPLAY "3. Monthly" DISPLAY "Enter choice (1-3):" READ frequency_choice AS NUMBER - + // Set compounding frequency IF frequency_choice == 1 THEN SET n TO 1 @@ -204,13 +204,13 @@ START PROGRAM SET n TO 1 SET frequency_name TO "Yearly" END IF - + // Calculate compound interest SET base TO 1 + (rate / n) SET exponent TO n * years SET final_amount TO principal * (base ^ exponent) SET total_interest TO final_amount - principal - + // Display results DISPLAY "Investment Summary" DISPLAY "------------------" @@ -221,7 +221,7 @@ START PROGRAM DISPLAY "Final Amount: $" + final_amount DISPLAY "Total Interest: $" + total_interest END PROGRAM -```rust +``` ### Analysis Breakdown @@ -260,7 +260,7 @@ END PROGRAM --- - **Great! You analyzed a complex mathematical problem!** + **Great! You analyzed a complex mathematical problem!** *Next: Interactive Problems!* @@ -280,42 +280,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```rs -fn main() { - println!("Hello, World!"); -} - -```rs - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard rust conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/rust/stage-3/level-4/lesson.md b/lessons/rust/stage-3/level-4/lesson.md index f833365..fffc24b 100644 --- a/lessons/rust/stage-3/level-4/lesson.md +++ b/lessons/rust/stage-3/level-4/lesson.md @@ -28,19 +28,19 @@ Interactive problems require handling multiple user inputs and decisions. You'll ### How to Run 1. **Compile the code**: - ```bash + ``` rustc hello.rs -o hello hello.rs - ```rust + ``` 2. **Run your program**: - ```bash + ``` ./hello hello - ```rust + ``` **Expected output:** -```rust +``` Hello, World! -```rust +``` ### Problem: Simple Banking System @@ -59,7 +59,7 @@ Create a simple banking system that allows users to perform basic banking operat 6. Show updated balance after each transaction **Menu Options:** -```rust +``` Simple Bank System ================== Current Balance: $1000.00 @@ -71,10 +71,10 @@ Choose an option: 4. Exit Enter your choice (1-4): -```rust +``` **Example Interaction:** -```rust +``` Simple Bank System ================== Current Balance: $1000.00 @@ -110,20 +110,20 @@ Choose an option: Enter your choice (1-4): 4 Thank you for using Simple Bank System! -```rust +``` --- ### How to Create Your Solution 1. **Navigate to your working directory**: - ```bash + ``` cd /path/to/your/folder - ```rust + ``` 2. **Create your pseudocode file**: - ```bash + ``` touch interactive_problems.md - ```rust + ``` 3. **Plan the main loop** - Program runs until user exits 4. **Design menu system** - Clear options for user 5. **Handle each operation** - Different logic for each choice @@ -181,7 +181,7 @@ Check the `VIM_CHEATSHEET.md` for editing commands! - **Exit Condition**: Clean program termination **Program Flow:** -```rust +``` Initialize balance WHILE user hasn't chosen exit: Display menu with current balance @@ -191,14 +191,14 @@ WHILE user hasn't chosen exit: Show confirmation END WHILE Display exit message -```rust +``` ### Sample Pseudocode Solution -```rust +``` START PROGRAM SET balance TO 1000.00 - + SET running TO true WHILE running == true DO // Display menu @@ -214,18 +214,18 @@ START PROGRAM DISPLAY "" DISPLAY "Enter your choice (1-4):" READ choice AS NUMBER - + // Process choice IF choice == 1 THEN // Check balance DISPLAY "Your current balance is: $" + balance DISPLAY "" - + ELSE IF choice == 2 THEN // Deposit DISPLAY "Enter deposit amount:" READ deposit_amount AS NUMBER - + IF deposit_amount > 0 THEN SET balance TO balance + deposit_amount DISPLAY "Deposit successful! New balance: $" + balance @@ -233,12 +233,12 @@ START PROGRAM DISPLAY "Invalid deposit amount. Please enter a positive number." END IF DISPLAY "" - + ELSE IF choice == 3 THEN // Withdraw DISPLAY "Enter withdrawal amount:" READ withdrawal_amount AS NUMBER - + IF withdrawal_amount > 0 AND withdrawal_amount <= balance THEN SET balance TO balance - withdrawal_amount DISPLAY "Withdrawal successful! New balance: $" + balance @@ -248,12 +248,12 @@ START PROGRAM DISPLAY "Insufficient funds. Your balance is $" + balance END IF DISPLAY "" - + ELSE IF choice == 4 THEN // Exit SET running TO false DISPLAY "Thank you for using Simple Bank System!" - + ELSE // Invalid choice DISPLAY "Invalid choice. Please select 1-4." @@ -261,7 +261,7 @@ START PROGRAM END IF END WHILE END PROGRAM -```rust +``` ### Analysis Breakdown @@ -302,7 +302,7 @@ END PROGRAM --- - **Great! You designed an interactive banking system!** + **Great! You designed an interactive banking system!** *Next: Decision-Based Problems!* @@ -322,42 +322,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```rs -fn main() { - println!("Hello, World!"); -} - -```rs - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard rust conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/rust/stage-3/level-5/lesson.md b/lessons/rust/stage-3/level-5/lesson.md index 891f696..433e32b 100644 --- a/lessons/rust/stage-3/level-5/lesson.md +++ b/lessons/rust/stage-3/level-5/lesson.md @@ -28,19 +28,19 @@ Decision-based problems require complex conditional logic and multiple decision ### How to Run 1. **Compile the code**: - ```bash + ``` rustc hello.rs -o hello hello.rs - ```rust + ``` 2. **Run your program**: - ```bash + ``` ./hello hello - ```rust + ``` **Expected output:** -```rust +``` Hello, World! -```rust +``` ### Problem: Travel Recommendation System @@ -77,7 +77,7 @@ Create a travel recommendation system that suggests destinations based on user p - Month: International destinations **Example Interaction:** -```rust +``` Travel Recommendation System =========================== @@ -126,20 +126,20 @@ Based on your preferences (Medium budget, Warm climate, Relaxation, Week-long tr - Cost estimate: $1800-2500 total - Duration: 7-14 days recommended - Activities: Beach relaxation, optional light adventure -```rust +``` --- ### How to Create Your Solution 1. **Navigate to your working directory**: - ```bash + ``` cd /path/to/your/folder - ```rust + ``` 2. **Create your pseudocode file**: - ```bash + ``` touch decision_based_problems.md - ```rust + ``` 3. **Map decision combinations** - Consider all possible preference combinations 4. **Design recommendation logic** - Match destinations to criteria 5. **Plan output formatting** - Clear, informative recommendations @@ -204,12 +204,12 @@ The problem requires a 4-dimensional decision matrix: ### Sample Pseudocode Solution -```rust +``` START PROGRAM DISPLAY "Travel Recommendation System" DISPLAY "===========================" DISPLAY "" - + // Get budget preference DISPLAY "What's your budget range?" DISPLAY "1. Low (under $1000)" @@ -217,7 +217,7 @@ START PROGRAM DISPLAY "3. High (over $3000)" DISPLAY "Enter choice (1-3):" READ budget_choice AS NUMBER - + // Get climate preference DISPLAY "What's your preferred climate?" DISPLAY "1. Cold" @@ -225,7 +225,7 @@ START PROGRAM DISPLAY "3. Warm" DISPLAY "Enter choice (1-3):" READ climate_choice AS NUMBER - + // Get activity preference DISPLAY "What's your activity preference?" DISPLAY "1. Relaxation" @@ -233,7 +233,7 @@ START PROGRAM DISPLAY "3. Culture" DISPLAY "Enter choice (1-3):" READ activity_choice AS NUMBER - + // Get duration preference DISPLAY "How long do you want to travel?" DISPLAY "1. Weekend (2-3 days)" @@ -241,34 +241,34 @@ START PROGRAM DISPLAY "3. Month (30 days)" DISPLAY "Enter choice (1-3):" READ duration_choice AS NUMBER - + // Convert choices to descriptive names SET budget_name TO "" IF budget_choice == 1 THEN SET budget_name TO "Low" ELSE IF budget_choice == 2 THEN SET budget_name TO "Medium" ELSE IF budget_choice == 3 THEN SET budget_name TO "High" - + SET climate_name TO "" IF climate_choice == 1 THEN SET climate_name TO "Cold" ELSE IF climate_choice == 2 THEN SET climate_name TO "Temperate" ELSE IF climate_choice == 3 THEN SET climate_name TO "Warm" - + SET activity_name TO "" IF activity_choice == 1 THEN SET activity_name TO "Relaxation" ELSE IF activity_choice == 2 THEN SET activity_name TO "Adventure" ELSE IF activity_choice == 3 THEN SET activity_name TO "Culture" - + SET duration_name TO "" IF duration_choice == 1 THEN SET duration_name TO "Weekend" ELSE IF duration_choice == 2 THEN SET duration_name TO "Week" ELSE IF duration_choice == 3 THEN SET duration_name TO "Month" - + // Display preferences summary DISPLAY "Based on your preferences (" + budget_name + " budget, " + climate_name + " climate, " + activity_name + ", " + duration_name + "-long trip):" DISPLAY "" DISPLAY " Recommended Destinations:" DISPLAY "" - + // Complex decision logic based on climate and activity (primary factors) IF climate_choice == 1 THEN // Cold climate IF activity_choice == 1 THEN // Relaxation + Cold @@ -283,7 +283,7 @@ START PROGRAM DISPLAY " - Cost estimate: $" + GET_COST_ESTIMATE(budget_choice, "aspen") DISPLAY " - Duration: 4-10 days recommended" DISPLAY " - Activities: Spas, fine dining, skiing optional" - + ELSE IF activity_choice == 2 THEN // Adventure + Cold DISPLAY "1. **Alaska**" DISPLAY " - Why: Extreme outdoor adventures" @@ -296,7 +296,7 @@ START PROGRAM DISPLAY " - Cost estimate: $" + GET_COST_ESTIMATE(budget_choice, "iceland") DISPLAY " - Duration: 5-10 days recommended" DISPLAY " - Activities: Hiking, hot springs, ice caves" - + ELSE // Culture + Cold DISPLAY "1. **Prague, Czech Republic**" DISPLAY " - Why: Historic architecture in cooler climate" @@ -310,7 +310,7 @@ START PROGRAM DISPLAY " - Duration: 3-7 days recommended" DISPLAY " - Activities: Castle visits, whiskey tours, festivals" END IF - + ELSE IF climate_choice == 2 THEN // Temperate climate IF activity_choice == 1 THEN // Relaxation + Temperate DISPLAY "1. **San Francisco, California**" @@ -324,7 +324,7 @@ START PROGRAM DISPLAY " - Cost estimate: $" + GET_COST_ESTIMATE(budget_choice, "portland") DISPLAY " - Duration: 4-10 days recommended" DISPLAY " - Activities: Coffee culture, gardens, light hiking" - + ELSE IF activity_choice == 2 THEN // Adventure + Temperate DISPLAY "1. **New Zealand South Island**" DISPLAY " - Why: Diverse outdoor adventures" @@ -337,7 +337,7 @@ START PROGRAM DISPLAY " - Cost estimate: $" + GET_COST_ESTIMATE(budget_choice, "colorado") DISPLAY " - Duration: 5-10 days recommended" DISPLAY " - Activities: Mountain biking, rock climbing, fishing" - + ELSE // Culture + Temperate DISPLAY "1. **Paris, France**" DISPLAY " - Why: World-class museums and cuisine" @@ -351,7 +351,7 @@ START PROGRAM DISPLAY " - Duration: 5-10 days recommended" DISPLAY " - Activities: Colosseum, Vatican, gelato tours" END IF - + ELSE // Warm climate IF activity_choice == 1 THEN // Relaxation + Warm DISPLAY "1. **Cancun, Mexico**" @@ -365,7 +365,7 @@ START PROGRAM DISPLAY " - Cost estimate: $" + GET_COST_ESTIMATE(budget_choice, "puerto_rico") DISPLAY " - Duration: 5-14 days flexible" DISPLAY " - Activities: Beach lounging, bioluminescent bays" - + ELSE IF activity_choice == 2 THEN // Adventure + Warm DISPLAY "1. **Costa Rica**" DISPLAY " - Why: Rainforest and beach adventures" @@ -378,7 +378,7 @@ START PROGRAM DISPLAY " - Cost estimate: $" + GET_COST_ESTIMATE(budget_choice, "hawaii") DISPLAY " - Duration: 7-10 days recommended" DISPLAY " - Activities: Volcano tours, snorkeling, hiking" - + ELSE // Culture + Warm DISPLAY "1. **Machu Picchu, Peru**" DISPLAY " - Why: Ancient Incan civilization" @@ -393,7 +393,7 @@ START PROGRAM DISPLAY " - Activities: Carnival, Christ statue, samba" END IF END IF - + DISPLAY "" DISPLAY "Safe travels! " END PROGRAM @@ -406,7 +406,7 @@ FUNCTION GET_COST_ESTIMATE(budget_level, destination) ELSE IF budget_level == 2 THEN RETURN "1500-2500" ELSE RETURN "3000-8000" END FUNCTION -```rust +``` ### Analysis Breakdown @@ -446,7 +446,7 @@ END FUNCTION --- - **Great! You designed a complex travel recommendation system!** + **Great! You designed a complex travel recommendation system!** *Next: Repetitive Problems!* @@ -466,42 +466,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```rs -fn main() { - println!("Hello, World!"); -} - -```rs - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard rust conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/rust/stage-3/level-6/lesson.md b/lessons/rust/stage-3/level-6/lesson.md index f91085a..ef09cbd 100644 --- a/lessons/rust/stage-3/level-6/lesson.md +++ b/lessons/rust/stage-3/level-6/lesson.md @@ -28,19 +28,19 @@ Repetitive problems require processing data in loops and handling repeated opera ### How to Run 1. **Compile the code**: - ```bash + ``` rustc hello.rs -o hello hello.rs - ```rust + ``` 2. **Run your program**: - ```bash + ``` ./hello hello - ```rust + ``` **Expected output:** -```rust +``` Hello, World! -```rust +``` ### Problem: Student Grade Analyzer @@ -67,7 +67,7 @@ Create a program that analyzes student grades and provides comprehensive statist - F: Below 60 **Example Interaction:** -```rust +``` Student Grade Analyzer ====================== @@ -117,20 +117,20 @@ Highest Average: Alice Johnson (90.75) Lowest Average: Bob Smith (78.33) Students Above Class Average: 2 Students Below Class Average: 1 -```rust +``` --- ### How to Create Your Solution 1. **Navigate to your working directory**: - ```bash + ``` cd /path/to/your/folder - ```rust + ``` 2. **Create your pseudocode file**: - ```bash + ``` touch repetitive_problems.md - ```rust + ``` 3. **Plan data structures** - How to store student information 4. **Design input loops** - Processing multiple students and grades 5. **Plan calculation logic** - Averages and statistics @@ -186,7 +186,7 @@ Check the `VIM_CHEATSHEET.md` for editing commands! - **Classification**: Convert numeric grades to letter grades **Processing Flow:** -```rust +``` Get student count FOR each student: Get student name @@ -199,19 +199,19 @@ FOR each student: Store student data Update class statistics Display comprehensive report -```rust +``` ### Sample Pseudocode Solution -```rust +``` START PROGRAM DISPLAY "Student Grade Analyzer" DISPLAY "======================" DISPLAY "" - + DISPLAY "How many students would you like to analyze?" READ student_count AS NUMBER - + // Initialize class statistics variables SET total_class_sum TO 0 SET total_grades_count TO 0 @@ -221,36 +221,36 @@ START PROGRAM SET lowest_student TO "" SET above_average_count TO 0 SET below_average_count TO 0 - + // Grade distribution counters SET grade_a_count TO 0 SET grade_b_count TO 0 SET grade_c_count TO 0 SET grade_d_count TO 0 SET grade_f_count TO 0 - + // Process each student FOR student_index FROM 1 TO student_count DO DISPLAY "--- Student " + student_index + " ---" - + DISPLAY "Enter student name:" READ student_name AS STRING - + DISPLAY "How many grades does " + student_name + " have?" READ grade_count AS NUMBER - + SET student_sum TO 0 - + // Get all grades for this student FOR grade_index FROM 1 TO grade_count DO DISPLAY "Enter grade " + grade_index + ":" READ grade AS NUMBER SET student_sum TO student_sum + grade END FOR - + // Calculate student average SET student_average TO student_sum / grade_count - + // Determine letter grade SET letter_grade TO "" IF student_average >= 90 THEN @@ -269,41 +269,41 @@ START PROGRAM SET letter_grade TO "F" SET grade_f_count TO grade_f_count + 1 END IF - + // Display student result DISPLAY student_name + " - Average: " + FORMAT_NUMBER(student_average, 2) + " (" + letter_grade + ")" DISPLAY "" - + // Update class statistics SET total_class_sum TO total_class_sum + student_sum SET total_grades_count TO total_grades_count + grade_count - + // Track highest and lowest IF student_average > highest_average THEN SET highest_average TO student_average SET highest_student TO student_name END IF - + IF student_average < lowest_average THEN SET lowest_average TO student_average SET lowest_student TO student_name END IF END FOR - + // Calculate overall class average SET class_average TO total_class_sum / total_grades_count - + // Count students above/below average (second pass would be needed for accuracy) // For simplicity, we'll count based on individual averages vs class average // In a real implementation, you'd store all student averages and compare - + // Display comprehensive report DISPLAY "Class Statistics Report" DISPLAY "=======================" DISPLAY "Total Students: " + student_count DISPLAY "Overall Class Average: " + FORMAT_NUMBER(class_average, 2) DISPLAY "" - + DISPLAY "Grade Distribution:" DISPLAY "A: " + grade_a_count + " student(s) (" + FORMAT_PERCENT(grade_a_count, student_count) + "%)" DISPLAY "B: " + grade_b_count + " student(s) (" + FORMAT_PERCENT(grade_b_count, student_count) + "%)" @@ -311,11 +311,11 @@ START PROGRAM DISPLAY "D: " + grade_d_count + " student(s) (" + FORMAT_PERCENT(grade_d_count, student_count) + "%)" DISPLAY "F: " + grade_f_count + " student(s) (" + FORMAT_PERCENT(grade_f_count, student_count) + "%)" DISPLAY "" - + DISPLAY "Performance Summary:" DISPLAY "Highest Average: " + highest_student + " (" + FORMAT_NUMBER(highest_average, 2) + ")" DISPLAY "Lowest Average: " + lowest_student + " (" + FORMAT_NUMBER(lowest_average, 2) + ")" - + // Note: Above/below average would require storing all student data DISPLAY "Students Above Class Average: [Would need stored data]" DISPLAY "Students Below Class Average: [Would need stored data]" @@ -332,7 +332,7 @@ FUNCTION FORMAT_PERCENT(count, total) SET percentage TO (count / total) * 100 RETURN FORMAT_NUMBER(percentage, 2) END FUNCTION -```rust +``` ### Analysis Breakdown @@ -372,7 +372,7 @@ END FUNCTION --- - **Great! You designed a comprehensive grade analysis system!** + **Great! You designed a comprehensive grade analysis system!** *Next: Complex System Problems!* @@ -392,42 +392,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```rs -fn main() { - println!("Hello, World!"); -} - -```rs - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard rust conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/rust/stage-3/level-7/lesson.md b/lessons/rust/stage-3/level-7/lesson.md index 6126684..43b09a0 100644 --- a/lessons/rust/stage-3/level-7/lesson.md +++ b/lessons/rust/stage-3/level-7/lesson.md @@ -28,19 +28,19 @@ Complex system problems require integrating multiple components and managing sys ### How to Run 1. **Compile the code**: - ```bash + ``` rustc hello.rs -o hello hello.rs - ```rust + ``` 2. **Run your program**: - ```bash + ``` ./hello hello - ```rust + ``` **Expected output:** -```rust +``` Hello, World! -```rust +``` ### Problem: Library Management System @@ -76,7 +76,7 @@ Create a comprehensive library management system that handles books, patrons, an - Books can be reserved when checked out **Example Interaction:** -```rust +``` Library Management System ========================= @@ -145,20 +145,20 @@ Overdue Books: 3 Total Fines Collected: $12.75 Most Popular Genre: Technology Most Popular Book: The Rust Programming Language (8 checkouts) -```rust +``` --- ### How to Create Your Solution 1. **Navigate to your working directory**: - ```bash + ``` cd /path/to/your/folder - ```rust + ``` 2. **Create your pseudocode file**: - ```bash + ``` touch complex_system_problems.md - ```rust + ``` 3. **Design system architecture** - Major components and their interactions 4. **Plan data structures** - How to store books, patrons, transactions 5. **Design menu system** - Navigation between different functions @@ -220,7 +220,7 @@ Check the `VIM_CHEATSHEET.md` for editing commands! - Transactions ↔ Time (due dates, overdue calculations) **System Flow:** -```rust +``` Main Loop: Display main menu Process user choice @@ -228,18 +228,18 @@ Main Loop: Handle transactions Update system state Return to main menu -```rust +``` ### Sample Pseudocode Solution -```rust +``` START PROGRAM // Initialize system data structures INITIALIZE_BOOK_CATALOG() INITIALIZE_PATRON_REGISTRY() INITIALIZE_CIRCULATION_RECORDS() INITIALIZE_RESERVATION_SYSTEM() - + SET running TO true WHILE running == true DO DISPLAY "Library Management System" @@ -254,7 +254,7 @@ START PROGRAM DISPLAY "" DISPLAY "Enter choice (1-5):" READ main_choice AS NUMBER - + IF main_choice == 1 THEN HANDLE_BOOK_MANAGEMENT() ELSE IF main_choice == 2 THEN @@ -286,7 +286,7 @@ PROCEDURE HANDLE_BOOK_MANAGEMENT() DISPLAY "" DISPLAY "Enter choice (1-5):" READ book_choice AS NUMBER - + IF book_choice == 1 THEN ADD_NEW_BOOK() ELSE IF book_choice == 2 THEN @@ -306,34 +306,34 @@ END PROCEDURE PROCEDURE ADD_NEW_BOOK() DISPLAY "Add New Book" DISPLAY "------------" - + DISPLAY "Enter ISBN:" READ isbn AS STRING - + // Check if book already exists IF BOOK_EXISTS(isbn) THEN DISPLAY "Book with this ISBN already exists!" RETURN END IF - + DISPLAY "Enter title:" READ title AS STRING - + DISPLAY "Enter author:" READ author AS STRING - + DISPLAY "Enter genre:" READ genre AS STRING - + DISPLAY "Enter publication year:" READ year AS NUMBER - + // Generate unique book ID SET book_id TO GENERATE_BOOK_ID() - + // Add to catalog ADD_BOOK_TO_CATALOG(book_id, isbn, title, author, genre, year, "available") - + DISPLAY "Book added successfully! ID: " + book_id END PROCEDURE @@ -346,12 +346,12 @@ PROCEDURE SEARCH_BOOKS() DISPLAY "3. Genre" DISPLAY "4. ISBN" READ search_type AS NUMBER - + DISPLAY "Enter search term:" READ search_term AS STRING - + SET results TO SEARCH_BOOK_CATALOG(search_type, search_term) - + IF results IS EMPTY THEN DISPLAY "No books found matching your search." ELSE @@ -375,7 +375,7 @@ PROCEDURE HANDLE_PATRON_MANAGEMENT() DISPLAY "" DISPLAY "Enter choice (1-5):" READ patron_choice AS NUMBER - + IF patron_choice == 1 THEN REGISTER_PATRON() ELSE IF patron_choice == 2 THEN @@ -395,22 +395,22 @@ END PROCEDURE PROCEDURE REGISTER_PATRON() DISPLAY "Register New Patron" DISPLAY "-------------------" - + DISPLAY "Enter full name:" READ name AS STRING - + DISPLAY "Enter email:" READ email AS STRING - + DISPLAY "Enter phone:" READ phone AS STRING - + // Generate unique patron ID SET patron_id TO GENERATE_PATRON_ID() - + // Add to registry ADD_PATRON_TO_REGISTRY(patron_id, name, email, phone, "active", 0.00) - + DISPLAY "Patron registered successfully! ID: " + patron_id END PROCEDURE @@ -428,7 +428,7 @@ PROCEDURE HANDLE_CIRCULATION() DISPLAY "" DISPLAY "Enter choice (1-6):" READ circulation_choice AS NUMBER - + IF circulation_choice == 1 THEN CHECK_OUT_BOOK() ELSE IF circulation_choice == 2 THEN @@ -450,34 +450,34 @@ END PROCEDURE PROCEDURE CHECK_OUT_BOOK() DISPLAY "Check Out Book" DISPLAY "--------------" - + DISPLAY "Enter patron ID:" READ patron_id AS STRING - + IF NOT PATRON_EXISTS(patron_id) THEN DISPLAY "Patron not found!" RETURN END IF - + // Check patron status and limits IF GET_PATRON_STATUS(patron_id) != "active" THEN DISPLAY "Patron account is not active." RETURN END IF - + IF GET_PATRON_CHECKOUT_COUNT(patron_id) >= 3 THEN DISPLAY "Patron has reached maximum checkout limit (3 books)." RETURN END IF - + DISPLAY "Enter book ID:" READ book_id AS STRING - + IF NOT BOOK_EXISTS_BY_ID(book_id) THEN DISPLAY "Book not found!" RETURN END IF - + IF GET_BOOK_STATUS(book_id) != "available" THEN DISPLAY "Book is not available for checkout." // Offer reservation @@ -489,14 +489,14 @@ PROCEDURE CHECK_OUT_BOOK() END IF RETURN END IF - + // Calculate due date (14 days from today) SET due_date TO CALCULATE_DUE_DATE(14) - + // Process checkout CHECKOUT_BOOK(patron_id, book_id, due_date) UPDATE_BOOK_STATUS(book_id, "checked_out") - + DISPLAY "Checkout Summary:" DISPLAY "Patron: " + GET_PATRON_NAME(patron_id) DISPLAY "Book: " + GET_BOOK_TITLE(book_id) @@ -507,49 +507,49 @@ END PROCEDURE PROCEDURE RETURN_BOOK() DISPLAY "Return Book" DISPLAY "-----------" - + DISPLAY "Enter book ID:" READ book_id AS STRING - + IF NOT BOOK_EXISTS_BY_ID(book_id) THEN DISPLAY "Book not found!" RETURN END IF - + IF GET_BOOK_STATUS(book_id) != "checked_out" THEN DISPLAY "This book is not checked out." RETURN END IF - + // Get checkout record SET checkout_record TO GET_CHECKOUT_RECORD(book_id) SET patron_id TO checkout_record.patron_id SET due_date TO checkout_record.due_date - + // Calculate any fines SET days_overdue TO CALCULATE_DAYS_OVERDUE(due_date) SET fine_amount TO 0.00 - + IF days_overdue > 0 THEN SET fine_amount TO days_overdue * 0.25 DISPLAY "Book is " + days_overdue + " days overdue." DISPLAY "Fine amount: $" + FORMAT_CURRENCY(fine_amount) - + // Add fine to patron account ADD_FINE_TO_PATRON(patron_id, fine_amount) END IF - + // Process return RETURN_BOOK_TRANSACTION(book_id) UPDATE_BOOK_STATUS(book_id, "available") - + // Check for reservations IF BOOK_HAS_RESERVATIONS(book_id) THEN SET next_reservation TO GET_NEXT_RESERVATION(book_id) NOTIFY_PATRON_OF_AVAILABLE_BOOK(next_reservation.patron_id, book_id) DISPLAY "Book is now reserved for another patron." END IF - + DISPLAY "Book returned successfully!" IF fine_amount > 0 THEN DISPLAY "Please pay fine amount at the circulation desk." @@ -569,7 +569,7 @@ PROCEDURE HANDLE_REPORTS() DISPLAY "" DISPLAY "Enter choice (1-5):" READ reports_choice AS NUMBER - + IF reports_choice == 1 THEN GENERATE_CIRCULATION_STATISTICS() ELSE IF reports_choice == 2 THEN @@ -589,9 +589,9 @@ END PROCEDURE PROCEDURE GENERATE_CIRCULATION_STATISTICS() DISPLAY "Circulation Statistics (Last 30 Days)" DISPLAY "=====================================" - + SET stats TO CALCULATE_CIRCULATION_STATS(30) - + DISPLAY "Total Checkouts: " + stats.total_checkouts DISPLAY "Total Returns: " + stats.total_returns DISPLAY "Currently Checked Out: " + stats.currently_checked_out @@ -644,7 +644,7 @@ FUNCTION FORMAT_CURRENCY(amount) // Format number as currency (e.g., 12.50 -> $12.50) RETURN "$" + amount END FUNCTION -```rust +``` ### Analysis Breakdown @@ -684,7 +684,7 @@ END FUNCTION --- - **Congratulations! You've designed a comprehensive library management system!** + **Congratulations! You've designed a comprehensive library management system!** *This completes Stage 3: Problem to Pseudocode! Ready for Stage 4: Full Problem Solving?* @@ -704,42 +704,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```rs -fn main() { - println!("Hello, World!"); -} - -```rs - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard rust conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/rust/stage-4/level-1/lesson.md b/lessons/rust/stage-4/level-1/lesson.md index 6b287a8..115c1fb 100644 --- a/lessons/rust/stage-4/level-1/lesson.md +++ b/lessons/rust/stage-4/level-1/lesson.md @@ -47,17 +47,17 @@ Based on your Stage 3 pseudocode, implement a temperature converter that: ### Implementation Steps 1. **Create the project structure**: - ```bash + ``` cd /home/eanhd/LEARN/rust/stage-4-full-problem-solving/level-1-simple-application - ```rust + ``` 2. **Create `main.rs`** with your Rust implementation 3. **Test your program**: - ```bash + ``` rustc main.rs ./main - ```rust + ``` 4. **Create `README.md`** with usage instructions @@ -135,7 +135,7 @@ Practice the code and experiment with variations! ### Expected Program Behavior -```rust +``` Temperature Converter ===================== What conversion do you want? @@ -153,11 +153,11 @@ What conversion do you want? Enter choice (1 or 2): 2 Enter temperature in Fahrenheit: 77 77°F is equal to 25°C -```rust +``` ### Sample Implementation -```rust +``` use std::io; fn main() { @@ -167,10 +167,10 @@ fn main() { println!("1. Celsius to Fahrenheit"); println!("2. Fahrenheit to Celsius"); print!("Enter choice (1 or 2): "); - + // Flush stdout to ensure prompt appears io::Write::flush(&mut io::stdout()).unwrap(); - + let mut choice = String::new(); io::stdin().read_line(&mut choice).unwrap(); let choice: u32 = match choice.trim().parse() { @@ -180,12 +180,12 @@ fn main() { return; } }; - + if choice == 1 { // Celsius to Fahrenheit print!("Enter temperature in Celsius: "); io::Write::flush(&mut io::stdout()).unwrap(); - + let mut celsius = String::new(); io::stdin().read_line(&mut celsius).unwrap(); let celsius: f64 = match celsius.trim().parse() { @@ -195,15 +195,15 @@ fn main() { return; } }; - + let fahrenheit = (celsius * 9.0 / 5.0) + 32.0; println!("{:.1}°C is equal to {:.1}°F", celsius, fahrenheit); - + } else if choice == 2 { // Fahrenheit to Celsius print!("Enter temperature in Fahrenheit: "); io::Write::flush(&mut io::stdout()).unwrap(); - + let mut fahrenheit = String::new(); io::stdin().read_line(&mut fahrenheit).unwrap(); let fahrenheit: f64 = match fahrenheit.trim().parse() { @@ -213,15 +213,15 @@ fn main() { return; } }; - + let celsius = (fahrenheit - 32.0) * 5.0 / 9.0; println!("{:.1}°F is equal to {:.1}°C", fahrenheit, celsius); - + } else { println!("Invalid choice. Please enter 1 or 2."); } } -```rust +``` ### Implementation Analysis @@ -268,7 +268,7 @@ fn main() { ### README.md Template -```markdown +``` # Temperature Converter A simple Rust program that converts temperatures between Celsius and Fahrenheit. @@ -276,14 +276,14 @@ A simple Rust program that converts temperatures between Celsius and Fahrenheit. ## How to Run 1. Compile the program: - ```bash + ``` rustc main.rs -```rust +``` 2. Run the program: - ```bash + ``` ./main -```rust +``` 3. Follow the on-screen prompts to convert temperatures. @@ -296,7 +296,7 @@ A simple Rust program that converts temperatures between Celsius and Fahrenheit. ## Example Usage -```rust +``` Temperature Converter ===================== What conversion do you want? @@ -305,8 +305,7 @@ What conversion do you want? Enter choice (1 or 2): 1 Enter temperature in Celsius: 25 25.0°C is equal to 77.0°F -```rust -```rust + ### Bonus Challenges @@ -317,7 +316,7 @@ Enter temperature in Celsius: 25 --- - **Congratulations! You built your first complete Rust application!** + **Congratulations! You built your first complete Rust application!** *Next: Data Processing Application (Student Grade Calculator)!* @@ -337,101 +336,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```rs -use std::io::{self, Write}; - -fn main() { - println!("Temperature Converter"); - println!("====================="); - println!("What conversion do you want?"); - println!("1. Celsius to Fahrenheit"); - println!("2. Fahrenheit to Celsius"); - print!("Enter choice (1 or 2): "); - - // Flush stdout to ensure prompt appears - io::stdout().flush().unwrap(); - - let mut choice = String::new(); - io::stdin().read_line(&mut choice).unwrap(); - let choice: u32 = match choice.trim().parse() { - Ok(num) => num, - Err(_) => { - println!("Invalid choice. Please enter 1 or 2."); - return; - } - }; - - if choice == 1 { - // Celsius to Fahrenheit - print!("Enter temperature in Celsius: "); - io::stdout().flush().unwrap(); - - let mut celsius = String::new(); - io::stdin().read_line(&mut celsius).unwrap(); - let celsius: f64 = match celsius.trim().parse() { - Ok(num) => num, - Err(_) => { - println!("Invalid temperature. Please enter a number."); - return; - } - }; - - let fahrenheit = (celsius * 9.0 / 5.0) + 32.0; - println!("{:.1}°C is equal to {:.1}°F", celsius, fahrenheit); - - } else if choice == 2 { - // Fahrenheit to Celsius - print!("Enter temperature in Fahrenheit: "); - io::stdout().flush().unwrap(); - - let mut fahrenheit = String::new(); - io::stdin().read_line(&mut fahrenheit).unwrap(); - let fahrenheit: f64 = match fahrenheit.trim().parse() { - Ok(num) => num, - Err(_) => { - println!("Invalid temperature. Please enter a number."); - return; - } - }; - - let celsius = (fahrenheit - 32.0) * 5.0 / 9.0; - println!("{:.1}°F is equal to {:.1}°C", fahrenheit, celsius); - - } else { - println!("Invalid choice. Please enter 1 or 2."); - } -} -```rs - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard rust conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/rust/stage-4/level-2/lesson.md b/lessons/rust/stage-4/level-2/lesson.md index dc9f11c..72dbf72 100644 --- a/lessons/rust/stage-4/level-2/lesson.md +++ b/lessons/rust/stage-4/level-2/lesson.md @@ -55,17 +55,17 @@ Based on your Stage 3 pseudocode, implement a student grade calculator that: ### Implementation Steps 1. **Create the project structure**: - ```bash + ``` cd /home/eanhd/LEARN/rust/stage-4-full-problem-solving/level-2-data-processing-application - ```rust + ``` 2. **Create `main.rs`** with your Rust implementation 3. **Test your program**: - ```bash + ``` rustc main.rs ./main - ```rust + ``` 4. **Create `README.md`** with usage instructions @@ -142,7 +142,7 @@ Practice the code and experiment with variations! ### Expected Program Behavior -```rust +``` Student Grade Calculator ======================== Enter student name: Alice Johnson @@ -157,11 +157,11 @@ Assignment 2: 92/100 (35%) Assignment 3: 78/100 (35%) Final Average: 84.9% Letter Grade: B -```rust +``` ### Sample Implementation -```rust +``` use std::io::{self, Write}; fn main() { @@ -225,7 +225,7 @@ fn get_valid_score(prompt: &str) -> f64 { } } } -```rust +``` ### Implementation Analysis @@ -270,7 +270,7 @@ fn get_valid_score(prompt: &str) -> f64 { ### README.md Template -```markdown +``` # Student Grade Calculator A Rust program that calculates weighted final grades for students based on assignment scores. @@ -278,14 +278,14 @@ A Rust program that calculates weighted final grades for students based on assig ## How to Run 1. Compile the program: - ```bash + ``` rustc main.rs -```rust +``` 2. Run the program: - ```bash + ``` ./main -```rust +``` 3. Enter student information and scores as prompted. @@ -298,7 +298,7 @@ A Rust program that calculates weighted final grades for students based on assig ## Example Usage -```rust +``` Student Grade Calculator ======================== Enter student name: Alice Johnson @@ -313,8 +313,7 @@ Assignment 2: 92/100 (35%) Assignment 3: 78/100 (35%) Final Average: 84.9% Letter Grade: B -```rust -```rust + ### Bonus Challenges @@ -325,7 +324,7 @@ Letter Grade: B --- - **Great! You built a data processing application!** + **Great! You built a data processing application!** *Next: Mathematical Application (Compound Interest Calculator)!* @@ -345,101 +344,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```rs -use std::io::{self, Write}; - -fn main() { - println!("Student Grade Calculator"); - println!("========================"); - - // Get student name - print!("Enter student name: "); - io::stdout().flush().unwrap(); - let mut student_name = String::new(); - io::stdin().read_line(&mut student_name).unwrap(); - let student_name = student_name.trim(); - - // Get assignment scores with validation - let score1 = get_valid_score("Enter Assignment 1 score (0-100): "); - let score2 = get_valid_score("Enter Assignment 2 score (0-100): "); - let score3 = get_valid_score("Enter Assignment 3 score (0-100): "); - - // Calculate weighted average - let weight1 = 0.30; - let weight2 = 0.35; - let weight3 = 0.35; - - let final_average = (score1 * weight1) + (score2 * weight2) + (score3 * weight3); - - // Determine letter grade - let letter_grade = if final_average >= 90.0 { - "A" - } else if final_average >= 80.0 { - "B" - } else if final_average >= 70.0 { - "C" - } else if final_average >= 60.0 { - "D" - } else { - "F" - }; - - // Display report - println!("\nStudent Report for {}", student_name); - println!("-------------------------------"); - println!("Assignment 1: {:.0}/100 (30%)", score1); - println!("Assignment 2: {:.0}/100 (35%)", score2); - println!("Assignment 3: {:.0}/100 (35%)", score3); - println!("Final Average: {:.1}%", final_average); - println!("Letter Grade: {}", letter_grade); -} - -fn get_valid_score(prompt: &str) -> f64 { - loop { - print!("{}", prompt); - io::stdout().flush().unwrap(); - - let mut input = String::new(); - io::stdin().read_line(&mut input).unwrap(); - - match input.trim().parse::() { - Ok(score) if score >= 0.0 && score <= 100.0 => return score, - Ok(_) => println!("Score must be between 0 and 100."), - Err(_) => println!("Please enter a valid number."), - } - } -} -```rs - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard rust conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/rust/stage-4/level-3/lesson.md b/lessons/rust/stage-4/level-3/lesson.md index d20c7c8..abdb3d0 100644 --- a/lessons/rust/stage-4/level-3/lesson.md +++ b/lessons/rust/stage-4/level-3/lesson.md @@ -39,9 +39,9 @@ Based on your Stage 3 pseudocode, implement a compound interest calculator that: 5. **Displays professional financial report** with all details **Compound Interest Formula:** -```rust +``` A = P(1 + r/n)^(nt) -```rust +``` Where: - A = Final amount - P = Principal amount @@ -59,17 +59,17 @@ Where: ### Implementation Steps 1. **Create the project structure**: - ```bash + ``` cd /home/eanhd/LEARN/rust/stage-4-full-problem-solving/level-3-mathematical-application - ```rust + ``` 2. **Create `main.rs`** with your Rust implementation 3. **Test your program**: - ```bash + ``` rustc main.rs ./main - ```rust + ``` 4. **Create `README.md`** with usage instructions @@ -146,7 +146,7 @@ Practice the code and experiment with variations! ### Expected Program Behavior -```rust +``` Compound Interest Calculator ============================ Enter principal amount: $1000 @@ -166,11 +166,11 @@ Years: 3 Compounding: Quarterly Final Amount: $1161.54 Total Interest: $161.54 -```rust +``` ### Sample Implementation -```rust +``` use std::io::{self, Write}; fn main() { @@ -282,7 +282,7 @@ fn get_valid_choice(prompt: &str, min: u32, max: u32) -> u32 { } } } -```rust +``` ### Implementation Analysis @@ -326,7 +326,7 @@ fn get_valid_choice(prompt: &str, min: u32, max: u32) -> u32 { ### README.md Template -```markdown +``` # Compound Interest Calculator A Rust program that calculates compound interest for savings and investments. @@ -334,14 +334,14 @@ A Rust program that calculates compound interest for savings and investments. ## How to Run 1. Compile the program: - ```bash + ``` rustc main.rs -```rust +``` 2. Run the program: - ```bash + ``` ./main -```rust +``` 3. Enter investment details as prompted. @@ -354,7 +354,7 @@ A Rust program that calculates compound interest for savings and investments. ## Example Usage -```rust +``` Compound Interest Calculator ============================ Enter principal amount: $1000 @@ -374,8 +374,7 @@ Years: 3 Compounding: Quarterly Final Amount: $1161.54 Total Interest: $161.54 -```rust -```rust + ### Bonus Challenges @@ -386,7 +385,7 @@ Total Interest: $161.54 --- - **Excellent! You built a mathematical financial application!** + **Excellent! You built a mathematical financial application!** *Next: Interactive Application (Simple Banking System)!* @@ -406,149 +405,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```rs -use std::io::{self, Write}; - -fn main() { - println!("Compound Interest Calculator"); - println!("============================"); - - // Get principal amount - let principal = get_positive_number("Enter principal amount: $"); - - // Get annual interest rate - let rate_percent = get_valid_rate("Enter annual interest rate (%): "); - let rate = rate_percent / 100.0; // Convert to decimal - - // Get number of years - let years = get_positive_integer("Enter number of years: "); - - // Get compounding frequency - println!("Compounding frequency:"); - println!("1. Yearly"); - println!("2. Quarterly"); - println!("3. Monthly"); - let frequency_choice = get_valid_choice("Enter choice (1-3): ", 1, 3); - - // Set compounding frequency values - let (n, frequency_name) = match frequency_choice { - 1 => (1.0, "Yearly"), - 2 => (4.0, "Quarterly"), - 3 => (12.0, "Monthly"), - _ => (1.0, "Yearly"), // Default fallback - }; - - // Calculate compound interest - let base = 1.0 + (rate / n); - let exponent = n * years as f64; - let final_amount = principal * base.powf(exponent); - let total_interest = final_amount - principal; - - // Display results - println!("\nInvestment Summary"); - println!("------------------"); - println!("Principal: ${:.2}", principal); - println!("Interest Rate: {:.2}%", rate_percent); - println!("Years: {}", years); - println!("Compounding: {}", frequency_name); - println!("Final Amount: ${:.2}", final_amount); - println!("Total Interest: ${:.2}", total_interest); -} - -fn get_positive_number(prompt: &str) -> f64 { - loop { - print!("{}", prompt); - io::stdout().flush().unwrap(); - - let mut input = String::new(); - io::stdin().read_line(&mut input).unwrap(); - - match input.trim().parse::() { - Ok(num) if num > 0.0 => return num, - Ok(_) => println!("Please enter a positive number."), - Err(_) => println!("Please enter a valid number."), - } - } -} - -fn get_valid_rate(prompt: &str) -> f64 { - loop { - print!("{}", prompt); - io::stdout().flush().unwrap(); - - let mut input = String::new(); - io::stdin().read_line(&mut input).unwrap(); - - match input.trim().parse::() { - Ok(rate) if rate >= 0.0 && rate <= 100.0 => return rate, - Ok(_) => println!("Rate must be between 0% and 100%."), - Err(_) => println!("Please enter a valid number."), - } - } -} - -fn get_positive_integer(prompt: &str) -> u32 { - loop { - print!("{}", prompt); - io::stdout().flush().unwrap(); - - let mut input = String::new(); - io::stdin().read_line(&mut input).unwrap(); - - match input.trim().parse::() { - Ok(num) if num > 0 => return num, - Ok(_) => println!("Please enter a positive number."), - Err(_) => println!("Please enter a valid integer."), - } - } -} - -fn get_valid_choice(prompt: &str, min: u32, max: u32) -> u32 { - loop { - print!("{}", prompt); - io::stdout().flush().unwrap(); - - let mut input = String::new(); - io::stdin().read_line(&mut input).unwrap(); - - match input.trim().parse::() { - Ok(choice) if choice >= min && choice <= max => return choice, - Ok(_) => println!("Please enter a number between {} and {}.", min, max), - Err(_) => println!("Please enter a valid number."), - } - } -} -```rs - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard rust conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/rust/stage-4/level-4/lesson.md b/lessons/rust/stage-4/level-4/lesson.md index 4fbd51e..7369e59 100644 --- a/lessons/rust/stage-4/level-4/lesson.md +++ b/lessons/rust/stage-4/level-4/lesson.md @@ -44,7 +44,7 @@ Based on your Stage 3 pseudocode, implement a simple banking system that: 6. **Maintains state** across multiple operations **Menu Structure:** -```rust +``` Simple Bank System ================== Current Balance: $1000.00 @@ -56,24 +56,24 @@ Choose an option: 4. Exit Enter your choice (1-4): -```rust +``` --- ### Implementation Steps 1. **Create the project structure**: - ```bash + ``` cd /home/eanhd/LEARN/rust/stage-4-full-problem-solving/level-4-interactive-application - ```rust + ``` 2. **Create `main.rs`** with your Rust implementation 3. **Test your program**: - ```bash + ``` rustc main.rs ./main - ```rust + ``` 4. **Create `README.md`** with usage instructions @@ -151,7 +151,7 @@ Practice the code and experiment with variations! ### Expected Program Behavior -```rust +``` Simple Bank System ================== Current Balance: $1000.00 @@ -176,11 +176,11 @@ Choose an option: Enter your choice (1-4): 4 Thank you for using Simple Bank System! -```rust +``` ### Sample Implementation -```rust +``` use std::io::{self, Write}; fn main() { @@ -283,7 +283,7 @@ fn get_positive_amount() -> f64 { } } } -```rust +``` ### Implementation Analysis @@ -331,7 +331,7 @@ fn get_positive_amount() -> f64 { ### README.md Template -```markdown +``` # Simple Banking System A Rust program that simulates basic banking operations with an interactive menu system. @@ -339,14 +339,14 @@ A Rust program that simulates basic banking operations with an interactive menu ## How to Run 1. Compile the program: - ```bash + ``` rustc main.rs -```rust +``` 2. Run the program: - ```bash + ``` ./main -```rust +``` 3. Use the menu to perform banking operations. @@ -360,7 +360,7 @@ A Rust program that simulates basic banking operations with an interactive menu ## Example Usage -```rust +``` Simple Bank System ================== Current Balance: $1000.00 @@ -375,8 +375,7 @@ Enter your choice (1-4): 2 Enter deposit amount: $500 Deposit successful! New balance: $1500.00 -```rust -```rust + ### Bonus Challenges @@ -387,7 +386,7 @@ Deposit successful! New balance: $1500.00 --- - **Fantastic! You built an interactive banking application!** + **Fantastic! You built an interactive banking application!** *Next: Decision Support Application (Travel Recommendation System)!* @@ -407,140 +406,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```rs -use std::io::{self, Write}; - -fn main() { - let mut balance = 1000.0; - let mut running = true; - - println!("Welcome to Simple Bank System!"); - - while running { - // Display menu with current balance - println!("\nSimple Bank System"); - println!("=================="); - println!("Current Balance: ${:.2}", balance); - println!(); - println!("Choose an option:"); - println!("1. Check Balance"); - println!("2. Deposit Money"); - println!("3. Withdraw Money"); - println!("4. Exit"); - println!(); - print!("Enter your choice (1-4): "); - io::stdout().flush().unwrap(); - - let choice = get_valid_choice(1, 4); - - match choice { - 1 => { - // Check balance - println!("Your current balance is: ${:.2}", balance); - } - 2 => { - // Deposit - print!("Enter deposit amount: $"); - io::stdout().flush().unwrap(); - let amount = get_positive_amount(); - - balance += amount; - println!("Deposit successful! New balance: ${:.2}", balance); - } - 3 => { - // Withdraw - print!("Enter withdrawal amount: $"); - io::stdout().flush().unwrap(); - let amount = get_positive_amount(); - - if amount <= balance { - balance -= amount; - println!("Withdrawal successful! New balance: ${:.2}", balance); - } else { - println!("Insufficient funds. Your balance is ${:.2}", balance); - } - } - 4 => { - // Exit - running = false; - println!("Thank you for using Simple Bank System!"); - } - _ => { - // This shouldn't happen due to validation, but just in case - println!("Invalid choice. Please select 1-4."); - } - } - } -} - -fn get_valid_choice(min: u32, max: u32) -> u32 { - loop { - let mut input = String::new(); - io::stdin().read_line(&mut input).unwrap(); - - match input.trim().parse::() { - Ok(choice) if choice >= min && choice <= max => return choice, - Ok(_) => { - print!("Please enter a number between {} and {}: ", min, max); - io::stdout().flush().unwrap(); - } - Err(_) => { - print!("Please enter a valid number: "); - io::stdout().flush().unwrap(); - } - } - } -} - -fn get_positive_amount() -> f64 { - loop { - let mut input = String::new(); - io::stdin().read_line(&mut input).unwrap(); - - match input.trim().parse::() { - Ok(amount) if amount > 0.0 => return amount, - Ok(_) => { - print!("Please enter a positive amount: $"); - io::stdout().flush().unwrap(); - } - Err(_) => { - print!("Please enter a valid number: $"); - io::stdout().flush().unwrap(); - } - } - } -} -```rs - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard rust conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/rust/stage-4/level-5/lesson.md b/lessons/rust/stage-4/level-5/lesson.md index 8acbea9..931bc42 100644 --- a/lessons/rust/stage-4/level-5/lesson.md +++ b/lessons/rust/stage-4/level-5/lesson.md @@ -54,17 +54,17 @@ Based on your Stage 3 pseudocode, implement a travel recommendation system that: ### Implementation Steps 1. **Create the project structure**: - ```bash + ``` cd /home/eanhd/LEARN/rust/stage-4-full-problem-solving/level-5-decision-support-application - ```rust + ``` 2. **Create `main.rs`** with your Rust implementation 3. **Test your program**: - ```bash + ``` rustc main.rs ./main - ```rust + ``` 4. **Create `README.md`** with usage instructions @@ -141,7 +141,7 @@ Practice the code and experiment with variations! ### Expected Program Behavior -```rust +``` Travel Recommendation System =========================== @@ -184,11 +184,11 @@ Based on your preferences (Medium budget, Warm climate, Relaxation, Week-long tr - Cost estimate: $1200-1800 total - Duration: 5-14 days flexible - Activities: Beach lounging, bioluminescent bays -```rust +``` ### Sample Implementation -```rust +``` use std::io::{self, Write}; fn main() { @@ -197,16 +197,16 @@ fn main() { println!(); // Get user preferences - let budget_choice = get_user_choice("What's your budget range?", + let budget_choice = get_user_choice("What's your budget range?", &["Low (under $1000)", "Medium ($1000-$3000)", "High (over $3000)"]); - let climate_choice = get_user_choice("What's your preferred climate?", + let climate_choice = get_user_choice("What's your preferred climate?", &["Cold", "Temperate", "Warm"]); - let activity_choice = get_user_choice("What's your activity preference?", + let activity_choice = get_user_choice("What's your activity preference?", &["Relaxation", "Adventure", "Culture"]); - let duration_choice = get_user_choice("How long do you want to travel?", + let duration_choice = get_user_choice("How long do you want to travel?", &["Weekend (2-3 days)", "Week (7 days)", "Month (30 days)"]); // Convert choices to descriptive names @@ -219,7 +219,7 @@ fn main() { let climate_name = match climate_choice { 1 => "Cold", - 2 => "Temperate", + 2 => "Temperate", 3 => "Warm", _ => "Unknown" }; @@ -239,7 +239,7 @@ fn main() { }; // Display preferences summary - println!("Based on your preferences ({} budget, {} climate, {}, {}-long trip):", + println!("Based on your preferences ({} budget, {} climate, {}, {}-long trip):", budget_name, climate_name, activity_name, duration_name); println!(); println!(" Recommended Destinations:"); @@ -358,68 +358,68 @@ fn display_destination(number: u32, name: &str, why: &str, cost_key: &str, durat // ===== DESTINATION RECOMMENDATION FUNCTIONS ===== fn recommend_cold_relaxation(budget: u32) { - display_destination(1, "Banff, Canada", "Mountain hot springs and luxury resorts", + display_destination(1, "Banff, Canada", "Mountain hot springs and luxury resorts", "banff", "3-7 days ideal", "Spa treatments, scenic views", budget); - display_destination(2, "Aspen, Colorado", "Luxury mountain relaxation", + display_destination(2, "Aspen, Colorado", "Luxury mountain relaxation", "aspen", "4-10 days recommended", "Spas, fine dining, skiing optional", budget); } fn recommend_cold_adventure(budget: u32) { - display_destination(1, "Alaska", "Extreme outdoor adventures", + display_destination(1, "Alaska", "Extreme outdoor adventures", "alaska", "7-14 days for full experience", "Glacier hiking, wildlife viewing", budget); - display_destination(2, "Iceland", "Volcanic landscapes and northern lights", + display_destination(2, "Iceland", "Volcanic landscapes and northern lights", "iceland", "5-10 days recommended", "Hiking, hot springs, ice caves", budget); } fn recommend_cold_culture(budget: u32) { - display_destination(1, "Prague, Czech Republic", "Historic architecture in cooler climate", + display_destination(1, "Prague, Czech Republic", "Historic architecture in cooler climate", "prague", "4-7 days ideal", "Castle tours, museums, Christmas markets", budget); - display_destination(2, "Edinburgh, Scotland", "Medieval history and festivals", + display_destination(2, "Edinburgh, Scotland", "Medieval history and festivals", "edinburgh", "3-7 days recommended", "Castle visits, whiskey tours, festivals", budget); } fn recommend_temperate_relaxation(budget: u32) { - display_destination(1, "San Francisco, California", "Mild weather with luxury amenities", + display_destination(1, "San Francisco, California", "Mild weather with luxury amenities", "sanfrancisco", "3-7 days ideal", "Spas, fine dining, bay cruises", budget); - display_destination(2, "Portland, Oregon", "Relaxed Pacific Northwest vibe", + display_destination(2, "Portland, Oregon", "Relaxed Pacific Northwest vibe", "portland", "4-10 days recommended", "Coffee culture, gardens, light hiking", budget); } fn recommend_temperate_adventure(budget: u32) { - display_destination(1, "New Zealand South Island", "Diverse outdoor adventures", + display_destination(1, "New Zealand South Island", "Diverse outdoor adventures", "nz_south", "7-14 days for full experience", "Bungee jumping, hiking, skiing", budget); - display_destination(2, "Colorado Rockies", "Mountain biking and hiking paradise", + display_destination(2, "Colorado Rockies", "Mountain biking and hiking paradise", "colorado", "5-10 days recommended", "Mountain biking, rock climbing, fishing", budget); } fn recommend_temperate_culture(budget: u32) { - display_destination(1, "Paris, France", "World-class museums and cuisine", + display_destination(1, "Paris, France", "World-class museums and cuisine", "paris", "4-7 days ideal", "Louvre, Eiffel Tower, cafes", budget); - display_destination(2, "Rome, Italy", "Ancient history and art", + display_destination(2, "Rome, Italy", "Ancient history and art", "rome", "5-10 days recommended", "Colosseum, Vatican, gelato tours", budget); } fn recommend_warm_relaxation(budget: u32) { - display_destination(1, "Cancun, Mexico", "Perfect warm beach relaxation", + display_destination(1, "Cancun, Mexico", "Perfect warm beach relaxation", "cancun", "7-10 days ideal", "Beach, spa, swimming with dolphins", budget); - display_destination(2, "Puerto Rico", "Caribbean warmth with relaxation focus", + display_destination(2, "Puerto Rico", "Caribbean warmth with relaxation focus", "puerto_rico", "5-14 days flexible", "Beach lounging, bioluminescent bays", budget); } fn recommend_warm_adventure(budget: u32) { - display_destination(1, "Costa Rica", "Rainforest and beach adventures", + display_destination(1, "Costa Rica", "Rainforest and beach adventures", "costa_rica", "7-14 days for full experience", "Zip-lining, surfing, volcano climbing", budget); - display_destination(2, "Hawaii Big Island", "Volcanic adventures and beaches", + display_destination(2, "Hawaii Big Island", "Volcanic adventures and beaches", "hawaii", "7-10 days recommended", "Volcano tours, snorkeling, hiking", budget); } fn recommend_warm_culture(budget: u32) { - display_destination(1, "Machu Picchu, Peru", "Ancient Incan civilization", + display_destination(1, "Machu Picchu, Peru", "Ancient Incan civilization", "machu_picchu", "7-10 days ideal", "Inca Trail, ancient ruins, Andean culture", budget); - display_destination(2, "Rio de Janeiro, Brazil", "Carnival culture and beaches", + display_destination(2, "Rio de Janeiro, Brazil", "Carnival culture and beaches", "rio", "5-14 days recommended", "Carnival, Christ statue, samba", budget); } -```rust +``` ### Implementation Analysis @@ -463,7 +463,7 @@ fn recommend_warm_culture(budget: u32) { ### README.md Template -```markdown +``` # Travel Recommendation System A Rust program that provides personalized travel destination recommendations based on user preferences for budget, climate, activities, and duration. @@ -471,14 +471,14 @@ A Rust program that provides personalized travel destination recommendations bas ## How to Run 1. Compile the program: - ```bash + ``` rustc main.rs -```rust +``` 2. Run the program: - ```bash + ``` ./main -```rust +``` 3. Answer the preference questions to get recommendations. @@ -499,7 +499,7 @@ A Rust program that provides personalized travel destination recommendations bas ## Example Output -```rust +``` Based on your preferences (Medium budget, Warm climate, Relaxation, Week-long trip): Recommended Destinations: @@ -509,8 +509,7 @@ Based on your preferences (Medium budget, Warm climate, Relaxation, Week-long tr - Cost estimate: $1500-2200 for flights + resort - Duration: 7-10 days ideal - Activities: Beach, spa, swimming with dolphins -```rust -```rust + ### Bonus Challenges @@ -521,7 +520,7 @@ Based on your preferences (Medium budget, Warm climate, Relaxation, Week-long tr --- - **Excellent! You built a sophisticated decision support system!** + **Excellent! You built a sophisticated decision support system!** *Next: Automated Application (Student Grade Analyzer)!* @@ -541,268 +540,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```rs -use std::io::{self, Write}; - -fn main() { - println!("Travel Recommendation System"); - println!("==========================="); - println!(); - - // Get user preferences - let budget_choice = get_user_choice("What's your budget range?", - &["Low (under $1000)", "Medium ($1000-$3000)", "High (over $3000)"]); - - let climate_choice = get_user_choice("What's your preferred climate?", - &["Cold", "Temperate", "Warm"]); - - let activity_choice = get_user_choice("What's your activity preference?", - &["Relaxation", "Adventure", "Culture"]); - - let duration_choice = get_user_choice("How long do you want to travel?", - &["Weekend (2-3 days)", "Week (7 days)", "Month (30 days)"]); - - // Convert choices to descriptive names - let budget_name = match budget_choice { - 1 => "Low", - 2 => "Medium", - 3 => "High", - _ => "Unknown" - }; - - let climate_name = match climate_choice { - 1 => "Cold", - 2 => "Temperate", - 3 => "Warm", - _ => "Unknown" - }; - - let activity_name = match activity_choice { - 1 => "Relaxation", - 2 => "Adventure", - 3 => "Culture", - _ => "Unknown" - }; - - let duration_name = match duration_choice { - 1 => "Weekend", - 2 => "Week", - 3 => "Month", - _ => "Unknown" - }; - - // Display preferences summary - println!("Based on your preferences ({} budget, {} climate, {}, {}-long trip):", - budget_name, climate_name, activity_name, duration_name); - println!(); - println!("🌴 Recommended Destinations:"); - println!(); - - // Complex decision logic based on climate and activity (primary factors) - match climate_choice { - 1 => { // Cold climate - match activity_choice { - 1 => recommend_cold_relaxation(budget_choice), // Relaxation + Cold - 2 => recommend_cold_adventure(budget_choice), // Adventure + Cold - 3 => recommend_cold_culture(budget_choice), // Culture + Cold - _ => println!("Invalid activity choice.") - } - } - 2 => { // Temperate climate - match activity_choice { - 1 => recommend_temperate_relaxation(budget_choice), // Relaxation + Temperate - 2 => recommend_temperate_adventure(budget_choice), // Adventure + Temperate - 3 => recommend_temperate_culture(budget_choice), // Culture + Temperate - _ => println!("Invalid activity choice.") - } - } - 3 => { // Warm climate - match activity_choice { - 1 => recommend_warm_relaxation(budget_choice), // Relaxation + Warm - 2 => recommend_warm_adventure(budget_choice), // Adventure + Warm - 3 => recommend_warm_culture(budget_choice), // Culture + Warm - _ => println!("Invalid activity choice.") - } - } - _ => println!("Invalid climate choice.") - } - - println!(); - println!("Safe travels! ✈️"); -} - -fn get_user_choice(question: &str, options: &[&str]) -> u32 { - println!("{}", question); - for (i, option) in options.iter().enumerate() { - println!("{}. {}", i + 1, option); - } - print!("Enter choice (1-{}): ", options.len()); - io::stdout().flush().unwrap(); - - loop { - let mut input = String::new(); - io::stdin().read_line(&mut input).unwrap(); - - match input.trim().parse::() { - Ok(choice) if choice >= 1 && choice <= options.len() as u32 => return choice, - Ok(_) => { - print!("Please enter a number between 1 and {}: ", options.len()); - io::stdout().flush().unwrap(); - } - Err(_) => { - print!("Please enter a valid number: "); - io::stdout().flush().unwrap(); - } - } - } -} - -fn get_cost_estimate(budget_level: u32, destination: &str) -> String { - match budget_level { - 1 => match destination { - "banff" | "aspen" => "600-900", - "alaska" | "iceland" => "800-1200", - "prague" | "edinburgh" => "400-700", - "sanfrancisco" | "portland" => "300-600", - "nz_south" | "colorado" => "800-1200", - "paris" | "rome" => "500-800", - "cancun" | "puerto_rico" => "400-700", - "costa_rica" | "hawaii" => "600-900", - "machu_picchu" | "rio" => "700-1000", - _ => "500-800" - }, - 2 => match destination { - "banff" | "aspen" => "1500-2500", - "alaska" | "iceland" => "2000-3000", - "prague" | "edinburgh" => "1000-1500", - "sanfrancisco" | "portland" => "800-1200", - "nz_south" | "colorado" => "1800-2800", - "paris" | "rome" => "1200-1800", - "cancun" | "puerto_rico" => "1200-1800", - "costa_rica" | "hawaii" => "1500-2200", - "machu_picchu" | "rio" => "1600-2400", - _ => "1200-1800" - }, - 3 => match destination { - "banff" | "aspen" => "4000-8000", - "alaska" | "iceland" => "5000-10000", - "prague" | "edinburgh" => "2500-4000", - "sanfrancisco" | "portland" => "2000-3500", - "nz_south" | "colorado" => "4500-9000", - "paris" | "rome" => "3000-5000", - "cancun" | "puerto_rico" => "2800-4500", - "costa_rica" | "hawaii" => "3500-6000", - "machu_picchu" | "rio" => "3800-6500", - _ => "3000-5000" - }, - _ => "1000-2000" - }.to_string() -} - -fn display_destination(number: u32, name: &str, why: &str, cost_key: &str, duration: &str, activities: &str, budget_level: u32) { - println!("{}. **{}**", number, name); - println!(" - Why: {}", why); - println!(" - Cost estimate: ${} total", get_cost_estimate(budget_level, cost_key)); - println!(" - Duration: {}", duration); - println!(" - Activities: {}", activities); - println!(); -} - -// ===== DESTINATION RECOMMENDATION FUNCTIONS ===== - -fn recommend_cold_relaxation(budget: u32) { - display_destination(1, "Banff, Canada", "Mountain hot springs and luxury resorts", - "banff", "3-7 days ideal", "Spa treatments, scenic views", budget); - display_destination(2, "Aspen, Colorado", "Luxury mountain relaxation", - "aspen", "4-10 days recommended", "Spas, fine dining, skiing optional", budget); -} - -fn recommend_cold_adventure(budget: u32) { - display_destination(1, "Alaska", "Extreme outdoor adventures", - "alaska", "7-14 days for full experience", "Glacier hiking, wildlife viewing", budget); - display_destination(2, "Iceland", "Volcanic landscapes and northern lights", - "iceland", "5-10 days recommended", "Hiking, hot springs, ice caves", budget); -} - -fn recommend_cold_culture(budget: u32) { - display_destination(1, "Prague, Czech Republic", "Historic architecture in cooler climate", - "prague", "4-7 days ideal", "Castle tours, museums, Christmas markets", budget); - display_destination(2, "Edinburgh, Scotland", "Medieval history and festivals", - "edinburgh", "3-7 days recommended", "Castle visits, whiskey tours, festivals", budget); -} - -fn recommend_temperate_relaxation(budget: u32) { - display_destination(1, "San Francisco, California", "Mild weather with luxury amenities", - "sanfrancisco", "3-7 days ideal", "Spas, fine dining, bay cruises", budget); - display_destination(2, "Portland, Oregon", "Relaxed Pacific Northwest vibe", - "portland", "4-10 days recommended", "Coffee culture, gardens, light hiking", budget); -} - -fn recommend_temperate_adventure(budget: u32) { - display_destination(1, "New Zealand South Island", "Diverse outdoor adventures", - "nz_south", "7-14 days for full experience", "Bungee jumping, hiking, skiing", budget); - display_destination(2, "Colorado Rockies", "Mountain biking and hiking paradise", - "colorado", "5-10 days recommended", "Mountain biking, rock climbing, fishing", budget); -} - -fn recommend_temperate_culture(budget: u32) { - display_destination(1, "Paris, France", "World-class museums and cuisine", - "paris", "4-7 days ideal", "Louvre, Eiffel Tower, cafes", budget); - display_destination(2, "Rome, Italy", "Ancient history and art", - "rome", "5-10 days recommended", "Colosseum, Vatican, gelato tours", budget); -} - -fn recommend_warm_relaxation(budget: u32) { - display_destination(1, "Cancun, Mexico", "Perfect warm beach relaxation", - "cancun", "7-10 days ideal", "Beach, spa, swimming with dolphins", budget); - display_destination(2, "Puerto Rico", "Caribbean warmth with relaxation focus", - "puerto_rico", "5-14 days flexible", "Beach lounging, bioluminescent bays", budget); -} - -fn recommend_warm_adventure(budget: u32) { - display_destination(1, "Costa Rica", "Rainforest and beach adventures", - "costa_rica", "7-14 days for full experience", "Zip-lining, surfing, volcano climbing", budget); - display_destination(2, "Hawaii Big Island", "Volcanic adventures and beaches", - "hawaii", "7-10 days recommended", "Volcano tours, snorkeling, hiking", budget); -} - -fn recommend_warm_culture(budget: u32) { - display_destination(1, "Machu Picchu, Peru", "Ancient Incan civilization", - "machu_picchu", "7-10 days ideal", "Inca Trail, ancient ruins, Andean culture", budget); - display_destination(2, "Rio de Janeiro, Brazil", "Carnival culture and beaches", - "rio", "5-14 days recommended", "Carnival, Christ statue, samba", budget); -} -```rs - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard rust conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/rust/stage-4/level-6/lesson.md b/lessons/rust/stage-4/level-6/lesson.md index eeacc63..a1f49b4 100644 --- a/lessons/rust/stage-4/level-6/lesson.md +++ b/lessons/rust/stage-4/level-6/lesson.md @@ -33,19 +33,19 @@ Now you'll implement an automated application that processes data in batches, re ### How to Run 1. **Compile the code**: - ```bash + ``` rustc hello.rs -o hello hello.rs - ```rust + ``` 2. **Run your program**: - ```bash + ``` ./hello hello - ```rust + ``` **Expected output:** -```rust +``` Hello, World! -```rust +``` ### Program Requirements @@ -70,19 +70,19 @@ Based on your Stage 3 pseudocode, implement a student grade analyzer that: ### Implementation Steps 1. **Create the project structure**: - ```bash + ``` cd /home/eanhd/LEARN/rust/stage-4-full-problem-solving/level-6-automated-application - ```rust + ``` 2. **Create `students.txt`** with sample data 3. **Create `main.rs`** with your Rust implementation 4. **Test your program**: - ```bash + ``` rustc main.rs ./main - ```rust + ``` 5. **Create `README.md`** with usage instructions @@ -151,7 +151,7 @@ Practice the code and experiment with variations! ### Expected Program Behavior -```rust +``` Student Grade Analyzer ====================== @@ -211,11 +211,11 @@ GPA: 1.00 Status: Needs improvement. Analysis complete! Reports saved to grade_report.txt -```rust +``` ### Sample Implementation -```rust +``` use std::fs; use std::io::Write; use std::collections::HashMap; @@ -433,7 +433,7 @@ fn save_report_to_file(students: &[Student]) -> Result<(), Box Result<(), Box Result<(), Box - -## Answer Key - -### Complete Solution - -```rs -use std::fs; -use std::io::Write; -use std::collections::HashMap; - -#[derive(Debug, Clone)] -struct Student { - id: u32, - name: String, - grades: HashMap, - average: f64, - letter_grade: String, - gpa: f64, -} - -impl Student { - fn new(id: u32, name: String, grades: HashMap) -> Self { - let average = Self::calculate_average(&grades); - let letter_grade = Self::calculate_letter_grade(average); - let gpa = Self::calculate_gpa(average); - - Student { - id, - name, - grades, - average, - letter_grade, - gpa, - } - } - - fn calculate_average(grades: &HashMap) -> f64 { - let sum: f64 = grades.values().sum(); - sum / grades.len() as f64 - } - - fn calculate_letter_grade(average: f64) -> String { - match average { - 90.0..=100.0 => "A", - 80.0..=89.9 => "B", - 70.0..=79.9 => "C", - 60.0..=69.9 => "D", - _ => "F", - }.to_string() - } - - fn calculate_gpa(average: f64) -> f64 { - match average { - 90.0..=100.0 => 4.0, - 80.0..=89.9 => 3.0, - 70.0..=79.9 => 2.0, - 60.0..=69.9 => 1.0, - _ => 0.0, - } - } - - fn get_status(&self) -> String { - match self.gpa { - 4.0 => "Excellent performance!", - 3.0 => "Good performance!", - 2.0 => "Satisfactory performance.", - 1.0 => "Needs improvement.", - _ => "Academic probation required.", - }.to_string() - } -} - -fn main() { - println!("Student Grade Analyzer"); - println!("======================"); - println!(); - - // Read student data from file - let students = match read_student_data("students.txt") { - Ok(students) => students, - Err(e) => { - println!("Error reading student data: {}", e); - println!("Make sure 'students.txt' exists in the current directory."); - return; - } - }; - - if students.is_empty() { - println!("No valid student data found in file."); - return; - } - - println!("Processing student data from file...\n"); - - // Generate and display reports - generate_class_summary(&students); - println!(); - generate_individual_reports(&students); - - // Save detailed report to file - if let Err(e) = save_report_to_file(&students) { - println!("Warning: Could not save report to file: {}", e); - } else { - println!("\nAnalysis complete! Reports saved to grade_report.txt"); - } -} - -fn read_student_data(filename: &str) -> Result, Box> { - let content = fs::read_to_string(filename)?; - let mut students = Vec::new(); - let mut line_number = 0; - - for line in content.lines() { - line_number += 1; - - // Skip empty lines and comments - if line.trim().is_empty() || line.starts_with('#') { - continue; - } - - let parts: Vec<&str> = line.split(',').map(|s| s.trim()).collect(); - if parts.len() < 3 { - eprintln!("Warning: Skipping malformed line {}: insufficient data", line_number); - continue; - } - - // Parse student ID - let id: u32 = match parts[0].parse() { - Ok(id) => id, - Err(_) => { - eprintln!("Warning: Skipping line {}: invalid student ID '{}'", line_number, parts[0]); - continue; - } - }; - - let name = parts[1].to_string(); - - // Parse grades - let mut grades = HashMap::new(); - let mut valid_grades = 0; - - for grade_part in &parts[2..] { - let grade_parts: Vec<&str> = grade_part.split(':').map(|s| s.trim()).collect(); - if grade_parts.len() == 2 { - let subject = grade_parts[0].to_string(); - match grade_parts[1].parse::() { - Ok(score) => { - if score >= 0.0 && score <= 100.0 { - grades.insert(subject, score); - valid_grades += 1; - } else { - eprintln!("Warning: Skipping invalid score {} for {} (must be 0-100)", score, subject); - } - } - Err(_) => { - eprintln!("Warning: Skipping invalid score '{}' for {}", grade_parts[1], subject); - } - } - } else { - eprintln!("Warning: Skipping malformed grade data: '{}'", grade_part); - } - } - - if valid_grades > 0 { - students.push(Student::new(id, name, grades)); - } else { - eprintln!("Warning: Skipping student {}: no valid grades found", name); - } - } - - Ok(students) -} - -fn generate_class_summary(students: &[Student]) { - println!("📊 CLASS SUMMARY REPORT"); - println!("======================"); - println!(); - - println!("Total Students: {}", students.len()); - - if students.is_empty() { - return; - } - - // Calculate class average GPA - let total_gpa: f64 = students.iter().map(|s| s.gpa).sum(); - let class_avg_gpa = total_gpa / students.len() as f64; - println!("Class Average GPA: {:.2}", class_avg_gpa); - - // Calculate grade distribution - let mut grade_counts = HashMap::new(); - for student in students { - *grade_counts.entry(student.letter_grade.clone()).or_insert(0) += 1; - } - - println!("Grade Distribution:"); - let grades = ["A", "B", "C", "D", "F"]; - for grade in &grades { - let count = grade_counts.get(*grade).unwrap_or(&0); - let percentage = if students.len() > 0 { - (*count as f64 / students.len() as f64) * 100.0 - } else { - 0.0 - }; - println!(" {}: {} students ({:.1}%)", grade, count, percentage); - } - - // Find top and bottom performers - if let Some(top_student) = students.iter().max_by(|a, b| a.gpa.partial_cmp(&b.gpa).unwrap()) { - println!("Top Performer: {} ({:.2} GPA)", top_student.name, top_student.gpa); - } - - if let Some(bottom_student) = students.iter().min_by(|a, b| a.gpa.partial_cmp(&b.gpa).unwrap()) { - println!("Needs Improvement: {} ({:.2} GPA)", bottom_student.name, bottom_student.gpa); - } -} - -fn generate_individual_reports(students: &[Student]) { - println!("📋 INDIVIDUAL STUDENT REPORTS"); - println!("==============================\n"); - - for student in students { - println!("Student: {}", student.name); - println!("ID: {}", student.id); - - // Display grades - print!("Grades: "); - let grade_strings: Vec = student.grades.iter() - .map(|(subject, score)| format!("{}:{:.0}", subject, score)) - .collect(); - println!("{}", grade_strings.join(", ")); - - println!("Average: {:.2}% ({})", student.average, student.letter_grade); - println!("GPA: {:.2}", student.gpa); - println!("Status: {}", student.get_status()); - println!(); - } -} - -fn save_report_to_file(students: &[Student]) -> Result<(), Box> { - let mut file = fs::File::create("grade_report.txt")?; - - // Get current date/time (simplified version) - let now = std::time::SystemTime::now(); - let datetime = format!("{:?}", now); // Simplified timestamp - - writeln!(file, "STUDENT GRADE ANALYSIS REPORT")?; - writeln!(file, "Generated: {}", datetime)?; - writeln!(file, "================================\n")?; - - // Class summary - writeln!(file, "CLASS SUMMARY")?; - writeln!(file, "-------------")?; - writeln!(file, "Total Students: {}", students.len())?; - - if !students.is_empty() { - let total_gpa: f64 = students.iter().map(|s| s.gpa).sum(); - let class_avg_gpa = total_gpa / students.len() as f64; - writeln!(file, "Class Average GPA: {:.2}", class_avg_gpa)?; - } - - // Grade distribution - let mut grade_counts = HashMap::new(); - for student in students { - *grade_counts.entry(student.letter_grade.clone()).or_insert(0) += 1; - } - - writeln!(file, "\nGrade Distribution:")?; - let grades = ["A", "B", "C", "D", "F"]; - for grade in &grades { - let count = grade_counts.get(*grade).unwrap_or(&0); - let percentage = if students.len() > 0 { - (*count as f64 / students.len() as f64) * 100.0 - } else { - 0.0 - }; - writeln!(file, " {}: {} students ({:.1}%)", grade, count, percentage)?; - } - - // Individual reports - writeln!(file, "\nINDIVIDUAL REPORTS")?; - writeln!(file, "------------------")?; - - for student in students { - writeln!(file, "\nStudent: {} (ID: {})", student.name, student.id)?; - - // Write grades - write!(file, "Grades: ")?; - let grade_strings: Vec = student.grades.iter() - .map(|(subject, score)| format!("{}:{:.0}", subject, score)) - .collect(); - writeln!(file, "{}", grade_strings.join(", "))?; - - writeln!(file, "Average: {:.2}% ({})", student.average, student.letter_grade)?; - writeln!(file, "GPA: {:.2}", student.gpa)?; - writeln!(file, "Status: {}", student.get_status())?; - } - - Ok(()) -} -```rs - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard rust conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/rust/stage-4/level-7/lesson.md b/lessons/rust/stage-4/level-7/lesson.md index 49d789a..e7b113c 100644 --- a/lessons/rust/stage-4/level-7/lesson.md +++ b/lessons/rust/stage-4/level-7/lesson.md @@ -34,19 +34,19 @@ ### How to Run 1. **Compile the code**: - ```bash + ``` rustc hello.rs -o hello hello.rs - ```rust + ``` 2. **Run your program**: - ```bash + ``` ./hello hello - ```rust + ``` **Expected output:** -```rust +``` Hello, World! -```rust +``` ### Program Requirements @@ -84,19 +84,19 @@ Based on your Stage 3 pseudocode, implement a complete library management system ### Implementation Steps 1. **Create the project structure**: - ```bash + ``` cd /home/eanhd/LEARN/rust/stage-4-full-problem-solving/level-7-capstone-project - ```rust + ``` 2. **Create `library_data.txt`** with initial data 3. **Create `main.rs`** with your complete Rust implementation 4. **Test your program**: - ```bash + ``` rustc main.rs ./main - ```rust + ``` 5. **Create `README.md`** with usage instructions @@ -166,7 +166,7 @@ Practice the code and experiment with variations! ### Expected Program Behavior -```rust +``` LIBRARY MANAGEMENT SYSTEM ============================== @@ -213,11 +213,11 @@ ISBN: 978-1593278281 Status: Available Found 1 book(s) matching "rust" -```rust +``` ### Sample Implementation -```rust +``` use std::fs; use std::io::{self, Write}; use std::collections::HashMap; @@ -1129,7 +1129,7 @@ fn get_numeric_input() -> Result { io::stdin().read_line(&mut input).unwrap(); input.trim().parse::() } -```rust +``` ### Implementation Analysis @@ -1183,7 +1183,7 @@ fn get_numeric_input() -> Result { ### README.md Template -```markdown +``` # Library Management System A comprehensive Rust application for managing library operations including book inventory, user management, and transaction tracking. @@ -1215,15 +1215,15 @@ A comprehensive Rust application for managing library operations including book - User Management (register, view, list users) - Transaction Management (checkout, return, view active) - Reports & Analytics (statistics, overdue, popular books) -```bash +``` --- - **Congratulations! You completed the entire Rust Programming Curriculum!** + **Congratulations! You completed the entire Rust Programming Curriculum!** *This capstone project demonstrates mastery of all 4 stages: copying code, pseudocode translation, problem design, and full problem solving. You've built a complete, professional-grade application!* - **Certificate of Completion** + **Certificate of Completion** *This certifies that you have successfully completed the comprehensive Rust Programming Learning Path, demonstrating proficiency in:* @@ -1266,952 +1266,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```rs -use std::fs; -use std::io::{self, Write}; -use std::collections::HashMap; -use std::time::{SystemTime, UNIX_EPOCH}; - -#[derive(Debug, Clone)] -enum BookStatus { - Available, - Borrowed { user_id: u32, due_date: u64 }, - Overdue { user_id: u32, due_date: u64 }, -} - -#[derive(Debug, Clone)] -struct Book { - id: u32, - title: String, - author: String, - isbn: String, - status: BookStatus, -} - -#[derive(Debug, Clone)] -struct User { - id: u32, - name: String, - email: String, - borrowed_books: Vec, // Book IDs - max_books: u32, -} - -#[derive(Debug, Clone)] -struct Transaction { - id: u32, - book_id: u32, - user_id: u32, - checkout_date: u64, - due_date: u64, - return_date: Option, - status: TransactionStatus, -} - -#[derive(Debug, Clone)] -enum TransactionStatus { - Active, - Returned, - Overdue, -} - -#[derive(Debug)] -struct Library { - books: HashMap, - users: HashMap, - transactions: HashMap, - next_book_id: u32, - next_user_id: u32, - next_transaction_id: u32, -} - -impl Library { - fn new() -> Self { - Library { - books: HashMap::new(), - users: HashMap::new(), - transactions: HashMap::new(), - next_book_id: 1, - next_user_id: 1, - next_transaction_id: 1, - } - } - - // ===== BOOK MANAGEMENT ===== - - fn add_book(&mut self, title: String, author: String, isbn: String) { - let book = Book { - id: self.next_book_id, - title, - author, - isbn, - status: BookStatus::Available, - }; - self.books.insert(self.next_book_id, book); - self.next_book_id += 1; - println!("✅ Book added successfully with ID: {}", self.next_book_id - 1); - } - - fn remove_book(&mut self, book_id: u32) -> Result<(), String> { - // Check if book exists and get its title before removal - let book_title = match self.books.get(&book_id) { - Some(book) => { - match book.status { - BookStatus::Available => book.title.clone(), - _ => return Err("Cannot remove book that is currently borrowed".to_string()) - } - } - None => return Err("Book not found".to_string()) - }; - - // Now remove the book - self.books.remove(&book_id); - println!("✅ Book '{}' removed successfully", book_title); - Ok(()) - } - - fn search_books(&self, search_type: &str, term: &str) -> Vec<&Book> { - let term_lower = term.to_lowercase(); - self.books.values().filter(|book| { - match search_type { - "title" => book.title.to_lowercase().contains(&term_lower), - "author" => book.author.to_lowercase().contains(&term_lower), - "isbn" => book.isbn.contains(&term_lower), - _ => book.title.to_lowercase().contains(&term_lower) || - book.author.to_lowercase().contains(&term_lower) || - book.isbn.contains(&term_lower) - } - }).collect() - } - - // ===== USER MANAGEMENT ===== - - fn add_user(&mut self, name: String, email: String) { - let user = User { - id: self.next_user_id, - name, - email, - borrowed_books: Vec::new(), - max_books: 3, // Default limit - }; - self.users.insert(self.next_user_id, user); - self.next_user_id += 1; - println!("✅ User added successfully with ID: {}", self.next_user_id - 1); - } - - fn get_user(&self, user_id: u32) -> Option<&User> { - self.users.get(&user_id) - } - - // ===== TRANSACTION MANAGEMENT ===== - - fn checkout_book(&mut self, book_id: u32, user_id: u32, days: u32) -> Result<(), String> { - // Validate book exists and is available - let book = self.books.get_mut(&book_id).ok_or("Book not found")?; - match book.status { - BookStatus::Available => {}, - _ => return Err("Book is not available".to_string()) - } - - // Validate user exists and has capacity - let user = self.users.get(&user_id).ok_or("User not found")?; - if user.borrowed_books.len() >= user.max_books as usize { - return Err("User has reached maximum book limit".to_string()); - } - - // Create transaction - let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs(); - let due_date = now + (days as u64 * 24 * 60 * 60); // days to seconds - - let transaction = Transaction { - id: self.next_transaction_id, - book_id, - user_id, - checkout_date: now, - due_date, - return_date: None, - status: TransactionStatus::Active, - }; - - // Update book status - book.status = BookStatus::Borrowed { user_id, due_date }; - - // Update user borrowed books - if let Some(user) = self.users.get_mut(&user_id) { - user.borrowed_books.push(book_id); - } - - // Store transaction - self.transactions.insert(self.next_transaction_id, transaction); - self.next_transaction_id += 1; - - println!("✅ Book checked out successfully!"); - println!(" Due date: {}", format_timestamp(due_date)); - - Ok(()) - } - - fn return_book(&mut self, book_id: u32, user_id: u32) -> Result<(), String> { - // Find active transaction - let transaction = self.transactions.values_mut() - .find(|t| t.book_id == book_id && t.user_id == user_id && - matches!(t.status, TransactionStatus::Active)) - .ok_or("No active transaction found for this book and user")?; - - // Update transaction - let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs(); - transaction.return_date = Some(now); - transaction.status = TransactionStatus::Returned; - - // Update book status - if let Some(book) = self.books.get_mut(&book_id) { - book.status = BookStatus::Available; - } - - // Update user borrowed books - if let Some(user) = self.users.get_mut(&user_id) { - user.borrowed_books.retain(|&id| id != book_id); - } - - println!("✅ Book returned successfully!"); - Ok(()) - } - - // ===== REPORTS & ANALYTICS ===== - - fn get_overdue_books(&self) -> Vec<&Book> { - let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs(); - self.books.values().filter(|book| { - matches!(book.status, BookStatus::Borrowed { .. } | BookStatus::Overdue { .. }) && - match book.status { - BookStatus::Borrowed { due_date, .. } => due_date < now, - BookStatus::Overdue { .. } => true, - _ => false - } - }).collect() - } - - fn generate_statistics(&self) { - println!("📊 LIBRARY STATISTICS"); - println!("===================="); - println!("Total Books: {}", self.books.len()); - println!("Total Users: {}", self.users.len()); - println!("Active Transactions: {}", - self.transactions.values().filter(|t| matches!(t.status, TransactionStatus::Active)).count()); - - let available_books = self.books.values().filter(|b| matches!(b.status, BookStatus::Available)).count(); - println!("Available Books: {}", available_books); - println!("Borrowed Books: {}", self.books.len() - available_books); - - let overdue = self.get_overdue_books(); - println!("Overdue Books: {}", overdue.len()); - } - - // ===== DATA PERSISTENCE ===== - - fn save_to_file(&self, filename: &str) -> Result<(), Box> { - let mut file = fs::File::create(filename)?; - - // Save metadata - writeln!(file, "LIBRARY_DATA_V1")?; - writeln!(file, "NEXT_IDS {} {} {}", self.next_book_id, self.next_user_id, self.next_transaction_id)?; - - // Save books - writeln!(file, "BOOKS {}", self.books.len())?; - for book in self.books.values() { - let status_str = match &book.status { - BookStatus::Available => "AVAILABLE".to_string(), - BookStatus::Borrowed { user_id, due_date } => format!("BORROWED {} {}", user_id, due_date), - BookStatus::Overdue { user_id, due_date } => format!("OVERDUE {} {}", user_id, due_date), - }; - writeln!(file, "{}|{}|{}|{}|{}", book.id, book.title, book.author, book.isbn, status_str)?; - } - - // Save users - writeln!(file, "USERS {}", self.users.len())?; - for user in self.users.values() { - let books_str = user.borrowed_books.iter().map(|id| id.to_string()).collect::>().join(","); - writeln!(file, "{}|{}|{}|{}", user.id, user.name, user.email, books_str)?; - } - - // Save transactions - writeln!(file, "TRANSACTIONS {}", self.transactions.len())?; - for transaction in self.transactions.values() { - let return_date_str = transaction.return_date.map_or("NONE".to_string(), |d| d.to_string()); - let status_str = match transaction.status { - TransactionStatus::Active => "ACTIVE", - TransactionStatus::Returned => "RETURNED", - TransactionStatus::Overdue => "OVERDUE", - }; - writeln!(file, "{}|{}|{}|{}|{}|{}|{}", - transaction.id, transaction.book_id, transaction.user_id, - transaction.checkout_date, transaction.due_date, return_date_str, status_str)?; - } - - Ok(()) - } - - fn load_from_file(&mut self, filename: &str) -> Result<(), Box> { - let content = fs::read_to_string(filename)?; - let mut lines = content.lines(); - - // Check version - let version = lines.next().ok_or("Invalid file format")?; - if version != "LIBRARY_DATA_V1" { - return Err("Unsupported file version".into()); - } - - // Load metadata - let next_ids_line = lines.next().ok_or("Missing metadata")?; - let parts: Vec<&str> = next_ids_line.split_whitespace().collect(); - if parts.len() >= 4 && parts[0] == "NEXT_IDS" { - self.next_book_id = parts[1].parse()?; - self.next_user_id = parts[2].parse()?; - self.next_transaction_id = parts[3].parse()?; - } - - // Load books - let books_header = lines.next().ok_or("Missing books section")?; - let parts: Vec<&str> = books_header.split_whitespace().collect(); - if parts.len() >= 2 && parts[0] == "BOOKS" { - let num_books: usize = parts[1].parse()?; - for _ in 0..num_books { - let line = lines.next().ok_or("Missing book data")?; - let parts: Vec<&str> = line.split('|').collect(); - if parts.len() >= 5 { - let id: u32 = parts[0].parse()?; - let title = parts[1].to_string(); - let author = parts[2].to_string(); - let isbn = parts[3].to_string(); - - let status = if parts[4] == "AVAILABLE" { - BookStatus::Available - } else { - let status_parts: Vec<&str> = parts[4].split_whitespace().collect(); - if status_parts.len() >= 3 { - let user_id: u32 = status_parts[1].parse()?; - let due_date: u64 = status_parts[2].parse()?; - if status_parts[0] == "BORROWED" { - BookStatus::Borrowed { user_id, due_date } - } else { - BookStatus::Overdue { user_id, due_date } - } - } else { - BookStatus::Available - } - }; - - let book = Book { id, title, author, isbn, status }; - self.books.insert(id, book); - } - } - } - - // Load users - let users_header = lines.next().ok_or("Missing users section")?; - let parts: Vec<&str> = users_header.split_whitespace().collect(); - if parts.len() >= 2 && parts[0] == "USERS" { - let num_users: usize = parts[1].parse()?; - for _ in 0..num_users { - let line = lines.next().ok_or("Missing user data")?; - let parts: Vec<&str> = line.split('|').collect(); - if parts.len() >= 4 { - let id: u32 = parts[0].parse()?; - let name = parts[1].to_string(); - let email = parts[2].to_string(); - let borrowed_books: Vec = if parts[3].is_empty() { - Vec::new() - } else { - parts[3].split(',').filter_map(|s| s.parse().ok()).collect() - }; - - let user = User { - id, - name, - email, - borrowed_books, - max_books: 3, - }; - self.users.insert(id, user); - } - } - } - - // Load transactions - let transactions_header = lines.next().ok_or("Missing transactions section")?; - let parts: Vec<&str> = transactions_header.split_whitespace().collect(); - if parts.len() >= 2 && parts[0] == "TRANSACTIONS" { - let num_transactions: usize = parts[1].parse()?; - for _ in 0..num_transactions { - let line = lines.next().ok_or("Missing transaction data")?; - let parts: Vec<&str> = line.split('|').collect(); - if parts.len() >= 7 { - let id: u32 = parts[0].parse()?; - let book_id: u32 = parts[1].parse()?; - let user_id: u32 = parts[2].parse()?; - let checkout_date: u64 = parts[3].parse()?; - let due_date: u64 = parts[4].parse()?; - let return_date = if parts[5] == "NONE" { - None - } else { - Some(parts[5].parse()?) - }; - let status = match parts[6] { - "ACTIVE" => TransactionStatus::Active, - "RETURNED" => TransactionStatus::Returned, - "OVERDUE" => TransactionStatus::Overdue, - _ => TransactionStatus::Active, - }; - - let transaction = Transaction { - id, book_id, user_id, checkout_date, due_date, return_date, status - }; - self.transactions.insert(id, transaction); - } - } - } - - Ok(()) - } -} - -fn format_timestamp(timestamp: u64) -> String { - // Simple timestamp formatting (could be enhanced with chrono crate) - format!("Timestamp: {}", timestamp) -} - -fn main() { - println!("🏛️ LIBRARY MANAGEMENT SYSTEM"); - println!("==============================\n"); - - let mut library = Library::new(); - - // Load existing data if available - if let Err(e) = library.load_from_file("library_data.txt") { - println!("No existing library data found ({}), starting fresh...", e); - } else { - println!("Library data loaded successfully!"); - } - println!(); - - // Main menu loop - loop { - display_main_menu(); - let choice = get_menu_choice(1, 5); - - match choice { - 1 => book_management_menu(&mut library), - 2 => user_management_menu(&mut library), - 3 => transaction_management_menu(&mut library), - 4 => reports_menu(&library), - 5 => { - // Save and exit - if let Err(e) = library.save_to_file("library_data.txt") { - println!("Warning: Could not save library data: {}", e); - } else { - println!("✅ Library data saved successfully!"); - } - println!("Thank you for using the Library Management System!"); - break; - } - _ => println!("Invalid choice. Please try again.") - } - println!(); - } -} - -fn display_main_menu() { - println!("Main Menu:"); - println!("1. Book Management"); - println!("2. User Management"); - println!("3. Transaction Management"); - println!("4. Reports & Analytics"); - println!("5. Save & Exit"); - print!("Enter choice (1-5): "); - io::stdout().flush().unwrap(); -} - -fn book_management_menu(library: &mut Library) { - loop { - println!("📚 BOOK MANAGEMENT"); - println!("=================="); - println!("1. Add New Book"); - println!("2. Remove Book"); - println!("3. Search Books"); - println!("4. Display All Books"); - println!("5. Display Available Books"); - println!("6. Back to Main Menu"); - print!("Enter choice (1-6): "); - io::stdout().flush().unwrap(); - - let choice = get_menu_choice(1, 6); - println!(); - - match choice { - 1 => add_book_interactive(library), - 2 => remove_book_interactive(library), - 3 => search_books_interactive(library), - 4 => display_all_books(library), - 5 => display_available_books(library), - 6 => break, - _ => println!("Invalid choice.") - } - println!(); - } -} - -fn add_book_interactive(library: &mut Library) { - println!("📖 ADD NEW BOOK"); - println!("==============="); - - print!("Enter book title: "); - io::stdout().flush().unwrap(); - let mut title = String::new(); - io::stdin().read_line(&mut title).unwrap(); - let title = title.trim().to_string(); - - print!("Enter author name: "); - io::stdout().flush().unwrap(); - let mut author = String::new(); - io::stdin().read_line(&mut author).unwrap(); - let author = author.trim().to_string(); - - print!("Enter ISBN: "); - io::stdout().flush().unwrap(); - let mut isbn = String::new(); - io::stdin().read_line(&mut isbn).unwrap(); - let isbn = isbn.trim().to_string(); - - library.add_book(title, author, isbn); -} - -fn remove_book_interactive(library: &mut Library) { - println!("🗑️ REMOVE BOOK"); - println!("==============="); - - print!("Enter book ID to remove: "); - io::stdout().flush().unwrap(); - let book_id: u32 = match get_numeric_input() { - Ok(id) => id, - Err(_) => { - println!("❌ Invalid book ID"); - return; - } - }; - - match library.remove_book(book_id) { - Ok(_) => {}, - Err(e) => println!("❌ Error: {}", e) - } -} - -fn search_books_interactive(library: &Library) { - println!("🔍 SEARCH BOOKS"); - println!("==============="); - println!("Search by:"); - println!("1. Title"); - println!("2. Author"); - println!("3. ISBN"); - println!("4. All fields"); - print!("Enter choice (1-4): "); - io::stdout().flush().unwrap(); - - let search_type_choice = get_menu_choice(1, 4); - let search_type = match search_type_choice { - 1 => "title", - 2 => "author", - 3 => "isbn", - 4 => "all", - _ => "all" - }; - - print!("Enter search term: "); - io::stdout().flush().unwrap(); - let mut term = String::new(); - io::stdin().read_line(&mut term).unwrap(); - let term = term.trim(); - - let results = library.search_books(search_type, term); - - println!("\nSearch Results:"); - println!("---------------"); - if results.is_empty() { - println!("No books found matching '{}'", term); - } else { - for book in &results { - display_book(book); - println!(); - } - println!("Found {} book(s) matching \"{}\"", results.len(), term); - } -} - -fn display_all_books(library: &Library) { - println!("📚 ALL BOOKS"); - println!("============"); - if library.books.is_empty() { - println!("No books in the library."); - } else { - for book in library.books.values() { - display_book(book); - println!(); - } - } -} - -fn display_available_books(library: &Library) { - println!("📚 AVAILABLE BOOKS"); - println!("=================="); - let available: Vec<&Book> = library.books.values() - .filter(|b| matches!(b.status, BookStatus::Available)) - .collect(); - - if available.is_empty() { - println!("No books currently available."); - } else { - for book in available { - display_book(book); - println!(); - } - } -} - -fn display_book(book: &Book) { - println!("Title: {}", book.title); - println!("Author: {}", book.author); - println!("ISBN: {}", book.isbn); - print!("Status: "); - match &book.status { - BookStatus::Available => println!("Available"), - BookStatus::Borrowed { user_id, due_date } => { - println!("Borrowed by user {} (Due: {})", user_id, format_timestamp(*due_date)); - } - BookStatus::Overdue { user_id, due_date } => { - println!("Overdue - borrowed by user {} (Was due: {})", user_id, format_timestamp(*due_date)); - } - } -} - -fn user_management_menu(library: &mut Library) { - loop { - println!("👥 USER MANAGEMENT"); - println!("=================="); - println!("1. Add New User"); - println!("2. View User Information"); - println!("3. Display All Users"); - println!("4. Back to Main Menu"); - print!("Enter choice (1-4): "); - io::stdout().flush().unwrap(); - - let choice = get_menu_choice(1, 4); - println!(); - - match choice { - 1 => add_user_interactive(library), - 2 => view_user_interactive(library), - 3 => display_all_users(library), - 4 => break, - _ => println!("Invalid choice.") - } - println!(); - } -} - -fn add_user_interactive(library: &mut Library) { - println!("👤 ADD NEW USER"); - println!("==============="); - - print!("Enter user name: "); - io::stdout().flush().unwrap(); - let mut name = String::new(); - io::stdin().read_line(&mut name).unwrap(); - let name = name.trim().to_string(); - - print!("Enter email address: "); - io::stdout().flush().unwrap(); - let mut email = String::new(); - io::stdin().read_line(&mut email).unwrap(); - let email = email.trim().to_string(); - - library.add_user(name, email); -} - -fn view_user_interactive(library: &Library) { - println!("👤 VIEW USER INFORMATION"); - println!("========================"); - - print!("Enter user ID: "); - io::stdout().flush().unwrap(); - let user_id: u32 = match get_numeric_input() { - Ok(id) => id, - Err(_) => { - println!("❌ Invalid user ID"); - return; - } - }; - - if let Some(user) = library.get_user(user_id) { - println!("User ID: {}", user.id); - println!("Name: {}", user.name); - println!("Email: {}", user.email); - println!("Max Books: {}", user.max_books); - println!("Currently Borrowed: {} books", user.borrowed_books.len()); - if !user.borrowed_books.is_empty() { - println!("Borrowed Book IDs: {:?}", user.borrowed_books); - } - } else { - println!("❌ User not found"); - } -} - -fn display_all_users(library: &Library) { - println!("👥 ALL USERS"); - println!("============"); - if library.users.is_empty() { - println!("No users registered."); - } else { - for user in library.users.values() { - println!("ID: {}, Name: {}, Email: {}, Borrowed: {} books", - user.id, user.name, user.email, user.borrowed_books.len()); - } - } -} - -fn transaction_management_menu(library: &mut Library) { - loop { - println!("🔄 TRANSACTION MANAGEMENT"); - println!("========================="); - println!("1. Checkout Book"); - println!("2. Return Book"); - println!("3. View Active Transactions"); - println!("4. Back to Main Menu"); - print!("Enter choice (1-4): "); - io::stdout().flush().unwrap(); - - let choice = get_menu_choice(1, 4); - println!(); - - match choice { - 1 => checkout_book_interactive(library), - 2 => return_book_interactive(library), - 3 => view_active_transactions(library), - 4 => break, - _ => println!("Invalid choice.") - } - println!(); - } -} - -fn checkout_book_interactive(library: &mut Library) { - println!("📖 CHECKOUT BOOK"); - println!("================="); - - print!("Enter book ID: "); - io::stdout().flush().unwrap(); - let book_id: u32 = match get_numeric_input() { - Ok(id) => id, - Err(_) => { - println!("❌ Invalid book ID"); - return; - } - }; - - print!("Enter user ID: "); - io::stdout().flush().unwrap(); - let user_id: u32 = match get_numeric_input() { - Ok(id) => id, - Err(_) => { - println!("❌ Invalid user ID"); - return; - } - }; - - print!("Enter loan period in days: "); - io::stdout().flush().unwrap(); - let days: u32 = match get_numeric_input() { - Ok(d) => d, - Err(_) => { - println!("❌ Invalid number of days"); - return; - } - }; - - match library.checkout_book(book_id, user_id, days) { - Ok(_) => {}, - Err(e) => println!("❌ Error: {}", e) - } -} - -fn return_book_interactive(library: &mut Library) { - println!("📚 RETURN BOOK"); - println!("=============="); - - print!("Enter book ID: "); - io::stdout().flush().unwrap(); - let book_id: u32 = match get_numeric_input() { - Ok(id) => id, - Err(_) => { - println!("❌ Invalid book ID"); - return; - } - }; - - print!("Enter user ID: "); - io::stdout().flush().unwrap(); - let user_id: u32 = match get_numeric_input() { - Ok(id) => id, - Err(_) => { - println!("❌ Invalid user ID"); - return; - } - }; - - match library.return_book(book_id, user_id) { - Ok(_) => {}, - Err(e) => println!("❌ Error: {}", e) - } -} - -fn view_active_transactions(library: &Library) { - println!("🔄 ACTIVE TRANSACTIONS"); - println!("======================"); - - let active: Vec<&Transaction> = library.transactions.values() - .filter(|t| matches!(t.status, TransactionStatus::Active)) - .collect(); - - if active.is_empty() { - println!("No active transactions."); - } else { - for transaction in active { - println!("Transaction ID: {}", transaction.id); - println!("Book ID: {}, User ID: {}", transaction.book_id, transaction.user_id); - println!("Checkout: {}, Due: {}", - format_timestamp(transaction.checkout_date), - format_timestamp(transaction.due_date)); - println!(); - } - } -} - -fn reports_menu(library: &Library) { - loop { - println!("📊 REPORTS & ANALYTICS"); - println!("======================="); - println!("1. Library Statistics"); - println!("2. Overdue Books"); - println!("3. Popular Books"); - println!("4. Back to Main Menu"); - print!("Enter choice (1-4): "); - io::stdout().flush().unwrap(); - - let choice = get_menu_choice(1, 4); - println!(); - - match choice { - 1 => library.generate_statistics(), - 2 => display_overdue_books(library), - 3 => display_popular_books(library), - 4 => break, - _ => println!("Invalid choice.") - } - println!(); - } -} - -fn display_overdue_books(library: &Library) { - println!("⚠️ OVERDUE BOOKS"); - println!("================="); - let overdue = library.get_overdue_books(); - - if overdue.is_empty() { - println!("No overdue books! 🎉"); - } else { - for book in &overdue { - display_book(book); - println!("---"); - } - println!("Total overdue: {} books", overdue.len()); - } -} - -fn display_popular_books(library: &Library) { - println!("📈 POPULAR BOOKS"); - println!("================="); - // Simple popularity based on transaction count - let mut book_transactions = HashMap::new(); - - for transaction in library.transactions.values() { - *book_transactions.entry(transaction.book_id).or_insert(0) += 1; - } - - let mut popular: Vec<(u32, u32)> = book_transactions.into_iter().collect(); - popular.sort_by(|a, b| b.1.cmp(&a.1)); - - if popular.is_empty() { - println!("No transaction data available."); - } else { - for (book_id, count) in popular.iter().take(5) { - if let Some(book) = library.books.get(book_id) { - println!("'{}' by {} - {} transactions", book.title, book.author, count); - } - } - } -} - -fn get_menu_choice(min: u32, max: u32) -> u32 { - loop { - let input = get_numeric_input(); - match input { - Ok(choice) if choice >= min && choice <= max => return choice, - Ok(_) => { - print!("Please enter a number between {} and {}: ", min, max); - io::stdout().flush().unwrap(); - } - Err(_) => { - print!("Please enter a valid number: "); - io::stdout().flush().unwrap(); - } - } - } -} - -fn get_numeric_input() -> Result { - let mut input = String::new(); - io::stdin().read_line(&mut input).unwrap(); - input.trim().parse::() -} -```rs - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard rust conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/rust/stage-5/level-1/lesson.md b/lessons/rust/stage-5/level-1/lesson.md index 0f5b323..2285319 100644 --- a/lessons/rust/stage-5/level-1/lesson.md +++ b/lessons/rust/stage-5/level-1/lesson.md @@ -7,7 +7,7 @@ ### Today's Mission -**Welcome to Stage 5!** +**Welcome to Stage 5!** You've completed Stages 1-4 and learned to: - Copy and understand code (Stage 1) @@ -38,9 +38,9 @@ By completing this capstone level, you will: Your Level 1 Capstone should: -**Complexity**: Moderate (3-5 main features) -**Code Size**: 500-1500 lines (depending on scope) -**Time Estimate**: 10-15 hours of focused work +**Complexity**: Moderate (3-5 main features) +**Code Size**: 500-1500 lines (depending on scope) +**Time Estimate**: 10-15 hours of focused work **Purpose**: Demonstrate mastery of Core Programming Concepts & Rust Principles --- @@ -193,7 +193,7 @@ Your capstone will be evaluated on: Before coding, submit a proposal addressing: -```rust +``` PROJECT TITLE: [Name] DOMAIN: [Category - e.g., Personal Finance, Education] PURPOSE: [What problem does it solve?] @@ -221,7 +221,7 @@ USER INTERFACE: - [What menus or prompts?] ESTIMATED EFFORT: [X hours of work] -```rust +``` --- @@ -240,10 +240,10 @@ Sketch out data structures and main functions. Plan the logic before implementing. **Step 5: Create Cargo Project** -```bash +``` cargo new my_capstone cd my_capstone -```rust +``` **Step 6: Start Coding** Implement one feature at a time, testing as you go. @@ -310,10 +310,10 @@ Once your core capstone is complete, consider these extensions: **Concepts You'll Need:** -From **Stage 1**: Syntax, operators, basic I/O -From **Stage 2**: Loops, conditionals, algorithms -From **Stage 3**: Functions, modularity, code organization -From **Stage 4**: File I/O, data structures, system design +From **Stage 1**: Syntax, operators, basic I/O +From **Stage 2**: Loops, conditionals, algorithms +From **Stage 3**: Functions, modularity, code organization +From **Stage 4**: File I/O, data structures, system design **Rust-Specific Concepts:** - Ownership and borrowing @@ -425,45 +425,45 @@ Practice the code and experiment with variations! **Essential Planning Steps:** 1. **Write a Problem Statement** -```rust +``` "My application solves [problem] by [approach] for [users] so that [outcome]." - ```rust + ``` 2. **Define Core Features** (3-5 minimum) -```rust +``` MUST HAVE (critical): - Feature A - Feature B - + SHOULD HAVE (important): - Feature C - Feature D - + NICE TO HAVE (bonus): - Feature E - ```rust + ``` 3. **Design Data Structures** - ```rust + ``` #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Person { pub id: usize, pub name: String, // ... other fields } - + pub struct Company { pub employees: Vec, pub name: String, // ... other fields } - ```rust + ``` 4. **Create Architecture Diagram** -```rust +``` USER INPUT ↓ MENU SYSTEM @@ -473,10 +473,10 @@ Practice the code and experiment with variations! DATA STORAGE (structs) ↓ FILE I/O (persistence) - ```rust + ``` 5. **Write Pseudocode for Main Functions** -```rust +``` Function: add_new_record(collection) 1. Get input from user 2. Validate input (return error if invalid) @@ -484,12 +484,12 @@ Practice the code and experiment with variations! 4. Add to collection 5. Save to file 6. Return success - + Function: search_records(collection, criteria) 1. Filter collection by criteria 2. Return matching records 3. Handle no matches case - ```rust + ``` ### Phase 3: Data Structure Design @@ -512,7 +512,7 @@ Practice the code and experiment with variations! **Design Pattern:** -```rust +``` use serde::{Serialize, Deserialize}; use std::error::Error; @@ -535,31 +535,31 @@ impl EntityManager { filename: filename.to_string(), } } - + pub fn add(&mut self, entity: Entity) -> Result<(), Box> { // Validation self.entities.push(entity); self.save()?; Ok(()) } - + pub fn save(&self) -> Result<(), Box> { // Serialization Ok(()) } - + pub fn load(&mut self) -> Result<(), Box> { // Deserialization Ok(()) } - + pub fn search(&self, criteria: &str) -> Vec<&Entity> { self.entities.iter() .filter(|e| e.name.contains(criteria)) .collect() } } -```rust +``` ### Phase 4: Implementation Strategy @@ -583,7 +583,7 @@ impl EntityManager { **Create a Test Plan:** -```rust +``` TEST CASE 1: Add New Record Input: Valid record data Expected: Record added, saved to file @@ -602,22 +602,22 @@ Result: PASS / FAIL > **NEEDS_AUTHOR:** Removed placeholder - verify completeness -```rust +``` **Unit Test Example:** -```rust +``` #[cfg(test)] mod tests { use super::*; - + #[test] fn test_add_entity() { let mut manager = EntityManager::new("test.json"); let entity = Entity { id: 1, name: "Test".to_string() }; assert!(manager.add(entity).is_ok()); } - + #[test] fn test_search_empty() { let manager = EntityManager::new("test.json"); @@ -625,7 +625,7 @@ mod tests { assert_eq!(results.len(), 0); } } -```rust +``` ### Phase 6: Code Quality Checklist @@ -660,9 +660,9 @@ mod tests { - Note which are core vs. bonus 3. **Building Instructions** - ```bash + ``` cargo build --release - ```rust + ``` 4. **Usage Guide** - How to run: `cargo run` @@ -697,14 +697,14 @@ mod tests { **An excellent capstone has:** - **Clear Purpose**: Solves a real or interesting problem - **Complete Implementation**: All features work, no partial functionality - **Robust Error Handling**: Uses Result types, handles edge cases - **Professional Code**: Follows Rust conventions, no warnings - **Thoughtful Design**: Data structures fit the problem - **Thorough Testing**: Unit tests + documented test cases - **Great Documentation**: README, doc comments, usage guide - **Personal Touch**: Shows creativity and individuality + **Clear Purpose**: Solves a real or interesting problem + **Complete Implementation**: All features work, no partial functionality + **Robust Error Handling**: Uses Result types, handles edge cases + **Professional Code**: Follows Rust conventions, no warnings + **Thoughtful Design**: Data structures fit the problem + **Thorough Testing**: Unit tests + documented test cases + **Great Documentation**: README, doc comments, usage guide + **Personal Touch**: Shows creativity and individuality --- @@ -737,18 +737,18 @@ mod tests { ## Real-World Capstone Examples ### Example 1: Personal Finance Manager -```rust +``` PURPOSE: Help track personal spending and savings goals -FEATURES: +FEATURES: - Add/categorize expenses - Set and track savings goals - Generate spending reports - Export to CSV for analysis COMPLEXITY: Moderate (5-7 hours) -```rust +``` ### Example 2: Quiz Application -```rust +``` PURPOSE: Interactive quiz system for learning FEATURES: - Load questions from file @@ -756,10 +756,10 @@ FEATURES: - Provide instant feedback - Show statistics and progress COMPLEXITY: Moderate (6-8 hours) -```rust +``` ### Example 3: Data Processor -```rust +``` PURPOSE: Analyze CSV files and generate reports FEATURES: - Parse CSV files @@ -768,15 +768,15 @@ FEATURES: - Generate reports - Export results COMPLEXITY: Moderate to Advanced (8-12 hours) -```rust +``` --- - **Congratulations on reaching Stage 5!** + **Congratulations on reaching Stage 5!** You've completed your programming education journey. Now create something amazing! -*Your capstone project is your proof to the world that you can program.* +*Your capstone project is your proof to the world that you can program.* @@ -809,42 +809,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```rs -fn main() { - println!("Hello, World!"); -} - -```rs - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard rust conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/rust/stage-5/level-2/lesson.md b/lessons/rust/stage-5/level-2/lesson.md index d412bbf..ea1898f 100644 --- a/lessons/rust/stage-5/level-2/lesson.md +++ b/lessons/rust/stage-5/level-2/lesson.md @@ -24,9 +24,9 @@ By the end of this level: ### Project Scope -**Complexity**: Intermediate-Advanced (5-7 features) -**Code Size**: 1500-3000 lines -**Time Estimate**: 15-20 hours +**Complexity**: Intermediate-Advanced (5-7 features) +**Code Size**: 1500-3000 lines +**Time Estimate**: 15-20 hours **Purpose**: Demonstrate advanced integration and system design --- @@ -205,42 +205,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```rs -fn main() { - println!("Hello, World!"); -} - -```rs - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard rust conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/rust/stage-5/level-3/lesson.md b/lessons/rust/stage-5/level-3/lesson.md index 4616d1c..f951918 100644 --- a/lessons/rust/stage-5/level-3/lesson.md +++ b/lessons/rust/stage-5/level-3/lesson.md @@ -24,9 +24,9 @@ By the end of this level: ### Project Scope -**Complexity**: Advanced (7-10 features) -**Code Size**: 2000-4000 lines -**Time Estimate**: 20-25 hours +**Complexity**: Advanced (7-10 features) +**Code Size**: 2000-4000 lines +**Time Estimate**: 20-25 hours **Purpose**: Showcase deep expertise in a specific domain --- @@ -182,42 +182,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```rs -fn main() { - println!("Hello, World!"); -} - -```rs - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard rust conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/rust/stage-5/level-4/lesson.md b/lessons/rust/stage-5/level-4/lesson.md index 097f6d2..4bc7539 100644 --- a/lessons/rust/stage-5/level-4/lesson.md +++ b/lessons/rust/stage-5/level-4/lesson.md @@ -58,19 +58,19 @@ Create a production-ready Data Visualization using Rust with: ### How to Run 1. **Compile the code**: - ```bash + ``` rustc hello.rs -o hello hello.rs - ```rust + ``` 2. **Run your program**: - ```bash + ``` ./hello hello - ```rust + ``` **Expected output:** -```rust +``` Hello, World! -```rust +``` ### How to Approach This @@ -227,42 +227,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```rs -fn main() { - println!("Hello, World!"); -} - -```rs - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard rust conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/rust/stage-5/level-5/lesson.md b/lessons/rust/stage-5/level-5/lesson.md index b51c1cd..d025ad4 100644 --- a/lessons/rust/stage-5/level-5/lesson.md +++ b/lessons/rust/stage-5/level-5/lesson.md @@ -58,19 +58,19 @@ Create a production-ready Automated Testing using Rust with: ### How to Run 1. **Compile the code**: - ```bash + ``` rustc hello.rs -o hello hello.rs - ```rust + ``` 2. **Run your program**: - ```bash + ``` ./hello hello - ```rust + ``` **Expected output:** -```rust +``` Hello, World! -```rust +``` ### How to Approach This @@ -227,42 +227,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```rs -fn main() { - println!("Hello, World!"); -} - -```rs - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard rust conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/rust/stage-5/level-6/lesson.md b/lessons/rust/stage-5/level-6/lesson.md index a312030..bf75fa9 100644 --- a/lessons/rust/stage-5/level-6/lesson.md +++ b/lessons/rust/stage-5/level-6/lesson.md @@ -58,19 +58,19 @@ Create a production-ready Performance Optimization using Rust with: ### How to Run 1. **Compile the code**: - ```bash + ``` rustc hello.rs -o hello hello.rs - ```rust + ``` 2. **Run your program**: - ```bash + ``` ./hello hello - ```rust + ``` **Expected output:** -```rust +``` Hello, World! -```rust +``` ### How to Approach This @@ -227,42 +227,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```rs -fn main() { - println!("Hello, World!"); -} - -```rs - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard rust conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/rust/stage-5/level-7/lesson.md b/lessons/rust/stage-5/level-7/lesson.md index 70fc2c2..aa5b73a 100644 --- a/lessons/rust/stage-5/level-7/lesson.md +++ b/lessons/rust/stage-5/level-7/lesson.md @@ -121,7 +121,7 @@ Now that you've completed your capstone journey: --- -### Congratulations! +### Congratulations! You've completed a comprehensive programming education: @@ -131,7 +131,7 @@ You've completed a comprehensive programming education: - **Stage 4**: Created problems independently - **Stage 5**: Built capstone projects professionally -**You are now a programmer.** +**You are now a programmer.** The journey doesn't end here—it's just beginning. Use your skills to: - Solve real problems @@ -233,42 +233,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```rs -fn main() { - println!("Hello, World!"); -} - -```rs - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard rust conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/shell/stage-1/level-1/lesson.md b/lessons/shell/stage-1/level-1/lesson.md index 8d574e6..c318fe8 100644 --- a/lessons/shell/stage-1/level-1/lesson.md +++ b/lessons/shell/stage-1/level-1/lesson.md @@ -21,20 +21,20 @@ Welcome to Shell Scripting! Today, you'll create your first bash script. Shell s Copy the following code EXACTLY as shown into a new file called `hello.sh`: -```bash +``` #!/bin/bash echo "Hello, World!" ``` ### How to Execute -```bash +``` bash hello.sh ``` Expected output: -```bash +``` Hello, World! ``` @@ -57,20 +57,23 @@ Hello, World! ## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -> **NEEDS_AUTHOR:** This lesson needs a complete answer key with code breakdown, execution process explanation, common errors table, and bonus knowledge section. Reference c-c++/stage-1/level-1/lesson.md for the gold standard format. +``` +#!/bin/bash +echo "Hello, World!" +``` -### Key Concepts +### Explanation -- Review the code structure specific to Shell -- Understand the execution flow -- Learn common pitfalls and solutions +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -### Next Steps +### Success Criteria -Practice the code and experiment with variations! +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -**Congratulations! Keep coding!** +**Great job! You've completed this lesson!** diff --git a/lessons/shell/stage-1/level-2/lesson.md b/lessons/shell/stage-1/level-2/lesson.md index d9d8096..18ea662 100644 --- a/lessons/shell/stage-1/level-2/lesson.md +++ b/lessons/shell/stage-1/level-2/lesson.md @@ -20,7 +20,7 @@ Now that you know how to run Shell programs, let's learn about variables! Variab Copy the following code EXACTLY as shown into a new file called `variables.sh`: -```sh +``` #!/bin/bash name="Alice" age=25 @@ -35,13 +35,13 @@ echo "Student status: $isStudent" ### How to Execute -```bash +``` bash variables.sh ``` Expected output: -```bash +``` Hello, Alice! You are 25 years old. Your height is 5.6 feet. @@ -86,21 +86,31 @@ Remember to check the `VIM_CHEATSHEET.md` in the root directory for basic Vim co ## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution + +``` +#!/bin/bash +name="Alice" +age=25 +height=5.6 +isStudent=true -> **NEEDS_AUTHOR:** This lesson needs a complete answer key with code breakdown, execution process explanation, common errors table, and bonus knowledge section. Reference c-c++/stage-1/level-1/lesson.md for the gold standard format. +echo "Hello, $name!" +echo "You are $age years old." +echo "Your height is $height feet." +echo "Student status: $isStudent" +``` -### Key Concepts +### Explanation -- Review the code structure specific to Shell -- Understand the execution flow -- Learn common pitfalls and solutions +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -### Next Steps +### Success Criteria -Practice the code and experiment with variations! +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -**Congratulations! Keep coding!** - +**Great job! You've completed this lesson!** diff --git a/lessons/shell/stage-1/level-3/lesson.md b/lessons/shell/stage-1/level-3/lesson.md index ca00525..8defef1 100644 --- a/lessons/shell/stage-1/level-3/lesson.md +++ b/lessons/shell/stage-1/level-3/lesson.md @@ -23,7 +23,7 @@ Master arithmetic operations and use the language as your calculator. **Copy the following code EXACTLY as shown below into `main.sh`** -```bash +``` #!/bin/bash a=15 @@ -60,7 +60,7 @@ echo "Precise Division: $x / $y = $(echo "scale=2; $x / $y" | bc)" ### The Complete Code -```bash +``` #!/bin/bash a=15 diff --git a/lessons/shell/stage-1/level-4/lesson.md b/lessons/shell/stage-1/level-4/lesson.md index 5e4fc9a..c8cd351 100644 --- a/lessons/shell/stage-1/level-4/lesson.md +++ b/lessons/shell/stage-1/level-4/lesson.md @@ -23,7 +23,7 @@ Make your programs interactive by reading input from users. **Copy the following code EXACTLY as shown below into `main.sh`** -```bash +``` #!/bin/bash read -p "Enter your name: " name @@ -54,7 +54,7 @@ echo "Next year you'll be $((age + 1))." ### The Complete Code -```bash +``` #!/bin/bash read -p "Enter your name: " name diff --git a/lessons/shell/stage-1/level-5/lesson.md b/lessons/shell/stage-1/level-5/lesson.md index 95ffe7e..82a62bb 100644 --- a/lessons/shell/stage-1/level-5/lesson.md +++ b/lessons/shell/stage-1/level-5/lesson.md @@ -23,7 +23,7 @@ Add decision-making to your programs with if/else statements. **Copy the following code EXACTLY as shown below into `main.sh`** -```bash +``` #!/bin/bash read -p "Enter a number: " num @@ -63,7 +63,7 @@ fi ### The Complete Code -```bash +``` #!/bin/bash read -p "Enter a number: " num diff --git a/lessons/shell/stage-1/level-6/lesson.md b/lessons/shell/stage-1/level-6/lesson.md index faf1696..831dd91 100644 --- a/lessons/shell/stage-1/level-6/lesson.md +++ b/lessons/shell/stage-1/level-6/lesson.md @@ -23,7 +23,7 @@ Learn to repeat actions efficiently using loops. **Copy the following code EXACTLY as shown below into `main.sh`** -```bash +``` #!/bin/bash echo "Counting 1 to 10:" @@ -66,7 +66,7 @@ echo "Liftoff!" ### The Complete Code -```bash +``` #!/bin/bash echo "Counting 1 to 10:" diff --git a/lessons/shell/stage-1/level-7/lesson.md b/lessons/shell/stage-1/level-7/lesson.md index 80b58b3..5cdea2b 100644 --- a/lessons/shell/stage-1/level-7/lesson.md +++ b/lessons/shell/stage-1/level-7/lesson.md @@ -23,7 +23,7 @@ Organize your code into reusable functions/methods. **Copy the following code EXACTLY as shown below into `main.sh`** -```bash +``` #!/bin/bash greet() { @@ -73,7 +73,7 @@ echo "5! = $fact" ### The Complete Code -```bash +``` #!/bin/bash greet() { diff --git a/lessons/shell/stage-2/level-1/lesson.md b/lessons/shell/stage-2/level-1/lesson.md index 2bcf9c3..a0c6128 100644 --- a/lessons/shell/stage-2/level-1/lesson.md +++ b/lessons/shell/stage-2/level-1/lesson.md @@ -20,7 +20,7 @@ Now that you know the basics, it's time to think like a programmer! You'll take Here's some pseudocode that describes a simple program: -```bash +``` START print "Welcome to the program!" print "This is my first real program" @@ -38,14 +38,14 @@ Hints: ### How to Run -```bash +``` cd ~/.local/share/learn/workspaces/shell/stage-2/level-1 bash main.sh ``` Expected output: -```bash +``` Welcome to the program! This is my first real program I'm learning to code! @@ -67,36 +67,28 @@ If you're stuck, here's what your code should look like (don't peek until you tr --- -## ANSWER KEY - -```sh -``` - -(Fill in based on language-specific syntax) - -```bash - ---- - -## What's Different About Stage 2? +## ANSWER KEY (No cheating until you've tried!) -**Stage 1 (Copying):** Code was provided, you typed it -**Stage 2 (Pseudocode→Code):** Logic is provided, you write the code +### Solution -This is a crucial step! You're now writing code from specifications, not just copying. This is how real programming works. - -### Key Concepts +``` +START + print "Welcome to the program!" + print "This is my first real program" + print "I'm learning to code!" +END +``` -- Pseudocode is language-independent - the same pseudocode could translate to many languages -- Your job is to understand the logic and implement it correctly -- Different languages have different syntax, but the logic is the same +### Explanation ---- +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -## Need Help with Vim? +### Success Criteria -Remember to check the `VIM_CHEATSHEET.md` in the root directory for basic Vim commands! +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -
+**Great job! You've completed this lesson!** diff --git a/lessons/shell/stage-2/level-2/lesson.md b/lessons/shell/stage-2/level-2/lesson.md index 489d384..103f50f 100644 --- a/lessons/shell/stage-2/level-2/lesson.md +++ b/lessons/shell/stage-2/level-2/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Shell:** -```bash +``` ALGORITHM: Variables in Algorithms BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` bash hello.sh ``` @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in Shell: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```bash +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/shell/stage-2/level-3/lesson.md b/lessons/shell/stage-2/level-3/lesson.md index ec3514d..771d0d4 100644 --- a/lessons/shell/stage-2/level-3/lesson.md +++ b/lessons/shell/stage-2/level-3/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Shell:** -```bash +``` ALGORITHM: Mathematical Algorithms BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` bash hello.sh ``` @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in Shell: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```bash +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/shell/stage-2/level-4/lesson.md b/lessons/shell/stage-2/level-4/lesson.md index f65f34a..c56afd4 100644 --- a/lessons/shell/stage-2/level-4/lesson.md +++ b/lessons/shell/stage-2/level-4/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Shell:** -```bash +``` ALGORITHM: Input/Output Algorithms BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` bash hello.sh ``` @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in Shell: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```bash +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/shell/stage-2/level-5/lesson.md b/lessons/shell/stage-2/level-5/lesson.md index eea29ea..4ad45bc 100644 --- a/lessons/shell/stage-2/level-5/lesson.md +++ b/lessons/shell/stage-2/level-5/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Shell:** -```bash +``` ALGORITHM: Decision Algorithms BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` bash hello.sh ``` @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in Shell: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```bash +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/shell/stage-2/level-6/lesson.md b/lessons/shell/stage-2/level-6/lesson.md index 0998050..4365e0b 100644 --- a/lessons/shell/stage-2/level-6/lesson.md +++ b/lessons/shell/stage-2/level-6/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Shell:** -```bash +``` ALGORITHM: Loop Algorithms BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` bash hello.sh ``` @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in Shell: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```bash +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/shell/stage-2/level-7/lesson.md b/lessons/shell/stage-2/level-7/lesson.md index 3614ed0..368f85f 100644 --- a/lessons/shell/stage-2/level-7/lesson.md +++ b/lessons/shell/stage-2/level-7/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Shell:** -```bash +``` ALGORITHM: Function Design BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` bash hello.sh ``` @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in Shell: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```bash +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/shell/stage-3/level-1/lesson.md b/lessons/shell/stage-3/level-1/lesson.md index 207e7db..aae12f0 100644 --- a/lessons/shell/stage-3/level-1/lesson.md +++ b/lessons/shell/stage-3/level-1/lesson.md @@ -22,7 +22,7 @@ You're now ready for Stage 3! This is where you start thinking like a real progr Step 1: Write the pseudocode first -```bash +``` What should happen: 1. Print "Hello, [name]" @@ -38,7 +38,7 @@ Create `main.shell.shell` with your solution. ### How to Run 1. **Run the code**: - ```bash + ``` bash hello.sh ``` @@ -87,21 +87,26 @@ Check the `VIM_CHEATSHEET.md` for basic Vim commands! ## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -> **NEEDS_AUTHOR:** This lesson needs a complete answer key with code breakdown, execution process explanation, common errors table, and bonus knowledge section. Reference c-c++/stage-1/level-1/lesson.md for the gold standard format. +``` +What should happen: +1. Print "Hello, [name]" -### Key Concepts +Write your pseudocode in plain English below: +(Your pseudocode here) +``` -- Review the code structure specific to Shell -- Understand the execution flow -- Learn common pitfalls and solutions +### Explanation -### Next Steps +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -Practice the code and experiment with variations! +### Success Criteria ---- +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does -**Congratulations! Keep coding!** +--- +**Great job! You've completed this lesson!** diff --git a/lessons/shell/stage-3/level-2/lesson.md b/lessons/shell/stage-3/level-2/lesson.md index 23fb5f2..bf9ca1f 100644 --- a/lessons/shell/stage-3/level-2/lesson.md +++ b/lessons/shell/stage-3/level-2/lesson.md @@ -51,7 +51,7 @@ Data Structure Planning - Design an algorithm to solve this problem, then implem ### How to Run 1. **Run the code**: - ```bash + ``` bash hello.sh ``` @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```bash +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/shell/stage-3/level-3/lesson.md b/lessons/shell/stage-3/level-3/lesson.md index 73015f2..b1ea6bf 100644 --- a/lessons/shell/stage-3/level-3/lesson.md +++ b/lessons/shell/stage-3/level-3/lesson.md @@ -51,7 +51,7 @@ Mathematical Problems - Design an algorithm to solve this problem, then implemen ### How to Run 1. **Run the code**: - ```bash + ``` bash hello.sh ``` @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```bash +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/shell/stage-3/level-4/lesson.md b/lessons/shell/stage-3/level-4/lesson.md index 5e7b1b9..3900901 100644 --- a/lessons/shell/stage-3/level-4/lesson.md +++ b/lessons/shell/stage-3/level-4/lesson.md @@ -51,7 +51,7 @@ Text Processing Problems - Design an algorithm to solve this problem, then imple ### How to Run 1. **Run the code**: - ```bash + ``` bash hello.sh ``` @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```bash +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/shell/stage-3/level-5/lesson.md b/lessons/shell/stage-3/level-5/lesson.md index 59cb24c..8c9807d 100644 --- a/lessons/shell/stage-3/level-5/lesson.md +++ b/lessons/shell/stage-3/level-5/lesson.md @@ -51,7 +51,7 @@ Logic Problems - Design an algorithm to solve this problem, then implement it. ### How to Run 1. **Run the code**: - ```bash + ``` bash hello.sh ``` @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```bash +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/shell/stage-3/level-6/lesson.md b/lessons/shell/stage-3/level-6/lesson.md index a1192bf..e64b840 100644 --- a/lessons/shell/stage-3/level-6/lesson.md +++ b/lessons/shell/stage-3/level-6/lesson.md @@ -51,7 +51,7 @@ Search Algorithms - Design an algorithm to solve this problem, then implement it ### How to Run 1. **Run the code**: - ```bash + ``` bash hello.sh ``` @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```bash +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/shell/stage-3/level-7/lesson.md b/lessons/shell/stage-3/level-7/lesson.md index 55b5b12..f0a6802 100644 --- a/lessons/shell/stage-3/level-7/lesson.md +++ b/lessons/shell/stage-3/level-7/lesson.md @@ -51,7 +51,7 @@ Sorting Algorithms - Design an algorithm to solve this problem, then implement i ### How to Run 1. **Run the code**: - ```bash + ``` bash hello.sh ``` @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```bash +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/shell/stage-4/level-1/lesson.md b/lessons/shell/stage-4/level-1/lesson.md index 1c86cf5..353b992 100644 --- a/lessons/shell/stage-4/level-1/lesson.md +++ b/lessons/shell/stage-4/level-1/lesson.md @@ -30,7 +30,7 @@ Requirements: ### How to Run 1. **Run the code**: - ```bash + ``` bash hello.sh ``` diff --git a/lessons/shell/stage-4/level-2/lesson.md b/lessons/shell/stage-4/level-2/lesson.md index 18402b3..3566c3e 100644 --- a/lessons/shell/stage-4/level-2/lesson.md +++ b/lessons/shell/stage-4/level-2/lesson.md @@ -51,7 +51,7 @@ Build a complete Text Analysis Tool application that: ### How to Run 1. **Run the code**: - ```bash + ``` bash hello.sh ``` @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```bash +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/shell/stage-4/level-3/lesson.md b/lessons/shell/stage-4/level-3/lesson.md index 85c7237..2623326 100644 --- a/lessons/shell/stage-4/level-3/lesson.md +++ b/lessons/shell/stage-4/level-3/lesson.md @@ -51,7 +51,7 @@ Build a complete Data Processing application that: ### How to Run 1. **Run the code**: - ```bash + ``` bash hello.sh ``` @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```bash +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/shell/stage-4/level-4/lesson.md b/lessons/shell/stage-4/level-4/lesson.md index c425b52..4c8ecdd 100644 --- a/lessons/shell/stage-4/level-4/lesson.md +++ b/lessons/shell/stage-4/level-4/lesson.md @@ -51,7 +51,7 @@ Build a complete File Operations application that: ### How to Run 1. **Run the code**: - ```bash + ``` bash hello.sh ``` @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```bash +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/shell/stage-4/level-5/lesson.md b/lessons/shell/stage-4/level-5/lesson.md index 268b1f6..06d9ba9 100644 --- a/lessons/shell/stage-4/level-5/lesson.md +++ b/lessons/shell/stage-4/level-5/lesson.md @@ -51,7 +51,7 @@ Build a complete API Integration application that: ### How to Run 1. **Run the code**: - ```bash + ``` bash hello.sh ``` @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```bash +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/shell/stage-4/level-6/lesson.md b/lessons/shell/stage-4/level-6/lesson.md index edf3390..6257379 100644 --- a/lessons/shell/stage-4/level-6/lesson.md +++ b/lessons/shell/stage-4/level-6/lesson.md @@ -51,7 +51,7 @@ Build a complete Database Operations application that: ### How to Run 1. **Run the code**: - ```bash + ``` bash hello.sh ``` @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```bash +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/shell/stage-4/level-7/lesson.md b/lessons/shell/stage-4/level-7/lesson.md index af67250..73eea0f 100644 --- a/lessons/shell/stage-4/level-7/lesson.md +++ b/lessons/shell/stage-4/level-7/lesson.md @@ -51,7 +51,7 @@ Build a complete Complete Application application that: ### How to Run 1. **Run the code**: - ```bash + ``` bash hello.sh ``` @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```bash +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/shell/stage-5/level-1/lesson.md b/lessons/shell/stage-5/level-1/lesson.md index ffdc7e9..6561493 100644 --- a/lessons/shell/stage-5/level-1/lesson.md +++ b/lessons/shell/stage-5/level-1/lesson.md @@ -30,7 +30,7 @@ You're going to build a complete Shell application. This is a real project that ### How to Run 1. **Run the code**: - ```bash + ``` bash hello.sh ``` diff --git a/lessons/shell/stage-5/level-2/lesson.md b/lessons/shell/stage-5/level-2/lesson.md index 1a70c65..6efd947 100644 --- a/lessons/shell/stage-5/level-2/lesson.md +++ b/lessons/shell/stage-5/level-2/lesson.md @@ -58,7 +58,7 @@ Create a production-ready CLI Tool using Shell with: ### How to Run 1. **Run the code**: - ```bash + ``` bash hello.sh ``` diff --git a/lessons/shell/stage-5/level-3/lesson.md b/lessons/shell/stage-5/level-3/lesson.md index 5fca4ac..22ef709 100644 --- a/lessons/shell/stage-5/level-3/lesson.md +++ b/lessons/shell/stage-5/level-3/lesson.md @@ -58,7 +58,7 @@ Create a production-ready REST API using Shell with: ### How to Run 1. **Run the code**: - ```bash + ``` bash hello.sh ``` diff --git a/lessons/shell/stage-5/level-4/lesson.md b/lessons/shell/stage-5/level-4/lesson.md index f271997..b44b71c 100644 --- a/lessons/shell/stage-5/level-4/lesson.md +++ b/lessons/shell/stage-5/level-4/lesson.md @@ -58,7 +58,7 @@ Create a production-ready Data Visualization using Shell with: ### How to Run 1. **Run the code**: - ```bash + ``` bash hello.sh ``` diff --git a/lessons/shell/stage-5/level-5/lesson.md b/lessons/shell/stage-5/level-5/lesson.md index a38176a..2333941 100644 --- a/lessons/shell/stage-5/level-5/lesson.md +++ b/lessons/shell/stage-5/level-5/lesson.md @@ -58,7 +58,7 @@ Create a production-ready Automated Testing using Shell with: ### How to Run 1. **Run the code**: - ```bash + ``` bash hello.sh ``` diff --git a/lessons/shell/stage-5/level-6/lesson.md b/lessons/shell/stage-5/level-6/lesson.md index ad60c6e..0b206b2 100644 --- a/lessons/shell/stage-5/level-6/lesson.md +++ b/lessons/shell/stage-5/level-6/lesson.md @@ -58,7 +58,7 @@ Create a production-ready Performance Optimization using Shell with: ### How to Run 1. **Run the code**: - ```bash + ``` bash hello.sh ``` diff --git a/lessons/shell/stage-5/level-7/lesson.md b/lessons/shell/stage-5/level-7/lesson.md index 3b6b076..0ce728e 100644 --- a/lessons/shell/stage-5/level-7/lesson.md +++ b/lessons/shell/stage-5/level-7/lesson.md @@ -58,7 +58,7 @@ Create a production-ready Final Capstone Project using Shell with: ### How to Run 1. **Run the code**: - ```bash + ``` bash hello.sh ``` diff --git a/lessons/sql/stage-1/level-1/lesson.md b/lessons/sql/stage-1/level-1/lesson.md index 5ae2d30..fbbc83c 100644 --- a/lessons/sql/stage-1/level-1/lesson.md +++ b/lessons/sql/stage-1/level-1/lesson.md @@ -21,19 +21,19 @@ Welcome to SQL! Today, you'll create your first SQL query. SQL (Structured Query Copy the following code EXACTLY as shown into a new file called `hello.sql`: -```sql +``` SELECT 'Hello, World!' AS message; ``` ### How to Execute -```bash +``` sqlite3 < hello.sql ``` Expected output: -```sql +``` Hello, World! ``` @@ -56,20 +56,22 @@ Hello, World! ## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -> **NEEDS_AUTHOR:** This lesson needs a complete answer key with code breakdown, execution process explanation, common errors table, and bonus knowledge section. Reference c-c++/stage-1/level-1/lesson.md for the gold standard format. +``` +SELECT 'Hello, World!' AS message; +``` -### Key Concepts +### Explanation -- Review the code structure specific to Sql -- Understand the execution flow -- Learn common pitfalls and solutions +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -### Next Steps +### Success Criteria -Practice the code and experiment with variations! +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -**Congratulations! Keep coding!** +**Great job! You've completed this lesson!** diff --git a/lessons/sql/stage-1/level-2/lesson.md b/lessons/sql/stage-1/level-2/lesson.md index 66cee08..56e304a 100644 --- a/lessons/sql/stage-1/level-2/lesson.md +++ b/lessons/sql/stage-1/level-2/lesson.md @@ -20,7 +20,7 @@ Now that you know how to run Sql programs, let's learn about variables! Variable Copy the following code EXACTLY as shown into a new file called `variables.sql`: -```sql +``` SELECT 'Alice' AS name, 25 AS age, @@ -30,13 +30,13 @@ SELECT ### How to Execute -```bash +``` sqlite3 variables.sql ``` Expected output: -```sql +``` Hello, Alice! You are 25 years old. Your height is 5.6 feet. @@ -81,21 +81,26 @@ Remember to check the `VIM_CHEATSHEET.md` in the root directory for basic Vim co ## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -> **NEEDS_AUTHOR:** This lesson needs a complete answer key with code breakdown, execution process explanation, common errors table, and bonus knowledge section. Reference c-c++/stage-1/level-1/lesson.md for the gold standard format. +``` +SELECT + 'Alice' AS name, + 25 AS age, + 5.6 AS height, + true AS isStudent; +``` -### Key Concepts +### Explanation -- Review the code structure specific to Sql -- Understand the execution flow -- Learn common pitfalls and solutions +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -### Next Steps +### Success Criteria -Practice the code and experiment with variations! +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -**Congratulations! Keep coding!** - +**Great job! You've completed this lesson!** diff --git a/lessons/sql/stage-1/level-3/lesson.md b/lessons/sql/stage-1/level-3/lesson.md index 0102e52..27b2549 100644 --- a/lessons/sql/stage-1/level-3/lesson.md +++ b/lessons/sql/stage-1/level-3/lesson.md @@ -23,9 +23,9 @@ Master arithmetic operations and use the language as your calculator. **Copy the following code EXACTLY as shown below into `main.sql`** -```sql +``` -- Math Operations in SQL -SELECT +SELECT 15 + 4 AS addition, 15 - 4 AS subtraction, 15 * 4 AS multiplication, @@ -54,9 +54,9 @@ SELECT ### The Complete Code -```sql +``` -- Math Operations in SQL -SELECT +SELECT 15 + 4 AS addition, 15 - 4 AS subtraction, 15 * 4 AS multiplication, diff --git a/lessons/sql/stage-1/level-4/lesson.md b/lessons/sql/stage-1/level-4/lesson.md index 9127a25..2014c10 100644 --- a/lessons/sql/stage-1/level-4/lesson.md +++ b/lessons/sql/stage-1/level-4/lesson.md @@ -23,13 +23,13 @@ Make your programs interactive by reading input from users. **Copy the following code EXACTLY as shown below into `main.sql`** -```sql +``` -- User Input Simulation (Using Variables) -- In a real SQL environment, you'd use parameters DECLARE @name VARCHAR(50) = 'Alice'; DECLARE @age INT = 25; -SELECT +SELECT 'Hello, ' + @name + '!' AS greeting, 'You are ' + CAST(@age AS VARCHAR) + ' years old.' AS age_message, 'Next year you''ll be ' + CAST(@age + 1 AS VARCHAR) + '.' AS next_year; @@ -55,13 +55,13 @@ SELECT ### The Complete Code -```sql +``` -- User Input Simulation (Using Variables) -- In a real SQL environment, you'd use parameters DECLARE @name VARCHAR(50) = 'Alice'; DECLARE @age INT = 25; -SELECT +SELECT 'Hello, ' + @name + '!' AS greeting, 'You are ' + CAST(@age AS VARCHAR) + ' years old.' AS age_message, 'Next year you''ll be ' + CAST(@age + 1 AS VARCHAR) + '.' AS next_year; diff --git a/lessons/sql/stage-1/level-5/lesson.md b/lessons/sql/stage-1/level-5/lesson.md index c0cf260..ba3135e 100644 --- a/lessons/sql/stage-1/level-5/lesson.md +++ b/lessons/sql/stage-1/level-5/lesson.md @@ -23,18 +23,18 @@ Add decision-making to your programs with if/else statements. **Copy the following code EXACTLY as shown below into `main.sql`** -```sql +``` -- Conditional Logic with CASE DECLARE @num INT = 15; -SELECT +SELECT @num AS number, - CASE + CASE WHEN @num > 0 THEN 'positive' WHEN @num < 0 THEN 'negative' ELSE 'zero' END AS sign, - CASE + CASE WHEN @num % 2 = 0 THEN 'even' ELSE 'odd' END AS parity; @@ -60,18 +60,18 @@ SELECT ### The Complete Code -```sql +``` -- Conditional Logic with CASE DECLARE @num INT = 15; -SELECT +SELECT @num AS number, - CASE + CASE WHEN @num > 0 THEN 'positive' WHEN @num < 0 THEN 'negative' ELSE 'zero' END AS sign, - CASE + CASE WHEN @num % 2 = 0 THEN 'even' ELSE 'odd' END AS parity; diff --git a/lessons/sql/stage-1/level-6/lesson.md b/lessons/sql/stage-1/level-6/lesson.md index 5ded359..c52c74c 100644 --- a/lessons/sql/stage-1/level-6/lesson.md +++ b/lessons/sql/stage-1/level-6/lesson.md @@ -23,7 +23,7 @@ Learn to repeat actions efficiently using loops. **Copy the following code EXACTLY as shown below into `main.sql`** -```sql +``` -- Loops using Recursive CTE WITH Numbers AS ( SELECT 1 AS n @@ -38,7 +38,7 @@ WITH Multiplier AS ( UNION ALL SELECT i + 1 FROM Multiplier WHERE i < 10 ) -SELECT +SELECT '7 × ' + CAST(i AS VARCHAR) + ' = ' + CAST(7 * i AS VARCHAR) AS result FROM Multiplier; @@ -73,7 +73,7 @@ SELECT 'Liftoff!' AS count; ### The Complete Code -```sql +``` -- Loops using Recursive CTE WITH Numbers AS ( SELECT 1 AS n @@ -88,7 +88,7 @@ WITH Multiplier AS ( UNION ALL SELECT i + 1 FROM Multiplier WHERE i < 10 ) -SELECT +SELECT '7 × ' + CAST(i AS VARCHAR) + ' = ' + CAST(7 * i AS VARCHAR) AS result FROM Multiplier; diff --git a/lessons/sql/stage-1/level-7/lesson.md b/lessons/sql/stage-1/level-7/lesson.md index dce14d6..a3b7724 100644 --- a/lessons/sql/stage-1/level-7/lesson.md +++ b/lessons/sql/stage-1/level-7/lesson.md @@ -23,7 +23,7 @@ Organize your code into reusable functions/methods. **Copy the following code EXACTLY as shown below into `main.sql`** -```sql +``` -- Functions in SQL CREATE FUNCTION dbo.Add(@a INT, @b INT) RETURNS INT @@ -38,18 +38,18 @@ AS BEGIN DECLARE @result INT = 1; DECLARE @i INT = 1; - + WHILE @i <= @n BEGIN SET @result = @result * @i; SET @i = @i + 1; END; - + RETURN @result; END; -- Using the functions -SELECT +SELECT 'Hello, Alice!' AS greeting1, 'Hello, Bob!' AS greeting2, dbo.Add(15, 7) AS sum, @@ -76,7 +76,7 @@ SELECT ### The Complete Code -```sql +``` -- Functions in SQL CREATE FUNCTION dbo.Add(@a INT, @b INT) RETURNS INT @@ -91,18 +91,18 @@ AS BEGIN DECLARE @result INT = 1; DECLARE @i INT = 1; - + WHILE @i <= @n BEGIN SET @result = @result * @i; SET @i = @i + 1; END; - + RETURN @result; END; -- Using the functions -SELECT +SELECT 'Hello, Alice!' AS greeting1, 'Hello, Bob!' AS greeting2, dbo.Add(15, 7) AS sum, diff --git a/lessons/sql/stage-2/level-1/lesson.md b/lessons/sql/stage-2/level-1/lesson.md index 1cc6f8c..4688856 100644 --- a/lessons/sql/stage-2/level-1/lesson.md +++ b/lessons/sql/stage-2/level-1/lesson.md @@ -20,7 +20,7 @@ Now that you know the basics, it's time to think like a programmer! You'll take Here's some pseudocode that describes a simple program: -```sql +``` START print "Welcome to the program!" print "This is my first real program" @@ -38,14 +38,14 @@ Hints: ### How to Run -```bash +``` cd ~/.local/share/learn/workspaces/sql/stage-2/level-1 sqlite3 main.sql ``` Expected output: -```sql +``` Welcome to the program! This is my first real program I'm learning to code! @@ -67,36 +67,28 @@ If you're stuck, here's what your code should look like (don't peek until you tr --- -## ANSWER KEY - -```sql -``` - -(Fill in based on language-specific syntax) - -```sql - ---- - -## What's Different About Stage 2? +## ANSWER KEY (No cheating until you've tried!) -**Stage 1 (Copying):** Code was provided, you typed it -**Stage 2 (Pseudocode→Code):** Logic is provided, you write the code +### Solution -This is a crucial step! You're now writing code from specifications, not just copying. This is how real programming works. - -### Key Concepts +``` +START + print "Welcome to the program!" + print "This is my first real program" + print "I'm learning to code!" +END +``` -- Pseudocode is language-independent - the same pseudocode could translate to many languages -- Your job is to understand the logic and implement it correctly -- Different languages have different syntax, but the logic is the same +### Explanation ---- +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -## Need Help with Vim? +### Success Criteria -Remember to check the `VIM_CHEATSHEET.md` in the root directory for basic Vim commands! +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -
+**Great job! You've completed this lesson!** diff --git a/lessons/sql/stage-2/level-2/lesson.md b/lessons/sql/stage-2/level-2/lesson.md index 4179b47..688426a 100644 --- a/lessons/sql/stage-2/level-2/lesson.md +++ b/lessons/sql/stage-2/level-2/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in SQL:** -```sql +``` ALGORITHM: Variables in Algorithms BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` sqlite3 < hello.sql ``` @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in SQL: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```sql +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/sql/stage-2/level-3/lesson.md b/lessons/sql/stage-2/level-3/lesson.md index de70759..25fee8e 100644 --- a/lessons/sql/stage-2/level-3/lesson.md +++ b/lessons/sql/stage-2/level-3/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in SQL:** -```sql +``` ALGORITHM: Mathematical Algorithms BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` sqlite3 < hello.sql ``` @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in SQL: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```sql +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/sql/stage-2/level-4/lesson.md b/lessons/sql/stage-2/level-4/lesson.md index 9368dd3..a1b28c5 100644 --- a/lessons/sql/stage-2/level-4/lesson.md +++ b/lessons/sql/stage-2/level-4/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in SQL:** -```sql +``` ALGORITHM: Input/Output Algorithms BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` sqlite3 < hello.sql ``` @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in SQL: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```sql +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/sql/stage-2/level-5/lesson.md b/lessons/sql/stage-2/level-5/lesson.md index 020df9d..863ec28 100644 --- a/lessons/sql/stage-2/level-5/lesson.md +++ b/lessons/sql/stage-2/level-5/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in SQL:** -```sql +``` ALGORITHM: Decision Algorithms BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` sqlite3 < hello.sql ``` @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in SQL: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```sql +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/sql/stage-2/level-6/lesson.md b/lessons/sql/stage-2/level-6/lesson.md index 050268e..3deb8e2 100644 --- a/lessons/sql/stage-2/level-6/lesson.md +++ b/lessons/sql/stage-2/level-6/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in SQL:** -```sql +``` ALGORITHM: Loop Algorithms BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` sqlite3 < hello.sql ``` @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in SQL: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```sql +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/sql/stage-2/level-7/lesson.md b/lessons/sql/stage-2/level-7/lesson.md index 1d1f817..de861b1 100644 --- a/lessons/sql/stage-2/level-7/lesson.md +++ b/lessons/sql/stage-2/level-7/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in SQL:** -```sql +``` ALGORITHM: Function Design BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` sqlite3 < hello.sql ``` @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in SQL: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```sql +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/sql/stage-3/level-1/lesson.md b/lessons/sql/stage-3/level-1/lesson.md index 40fb8c4..607bafe 100644 --- a/lessons/sql/stage-3/level-1/lesson.md +++ b/lessons/sql/stage-3/level-1/lesson.md @@ -22,7 +22,7 @@ You're now ready for Stage 3! This is where you start thinking like a real progr Step 1: Write the pseudocode first -```sql +``` What should happen: 1. Print "Hello, [name]" @@ -38,7 +38,7 @@ Create `main.sql.sql` with your solution. ### How to Run 1. **Run the code**: - ```bash + ``` sqlite3 < hello.sql ``` @@ -87,21 +87,26 @@ Check the `VIM_CHEATSHEET.md` for basic Vim commands! ## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -> **NEEDS_AUTHOR:** This lesson needs a complete answer key with code breakdown, execution process explanation, common errors table, and bonus knowledge section. Reference c-c++/stage-1/level-1/lesson.md for the gold standard format. +``` +What should happen: +1. Print "Hello, [name]" -### Key Concepts +Write your pseudocode in plain English below: +(Your pseudocode here) +``` -- Review the code structure specific to Sql -- Understand the execution flow -- Learn common pitfalls and solutions +### Explanation -### Next Steps +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -Practice the code and experiment with variations! +### Success Criteria ---- +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does -**Congratulations! Keep coding!** +--- +**Great job! You've completed this lesson!** diff --git a/lessons/sql/stage-3/level-2/lesson.md b/lessons/sql/stage-3/level-2/lesson.md index 80b006c..c189c96 100644 --- a/lessons/sql/stage-3/level-2/lesson.md +++ b/lessons/sql/stage-3/level-2/lesson.md @@ -51,7 +51,7 @@ Data Structure Planning - Design an algorithm to solve this problem, then implem ### How to Run 1. **Run the code**: - ```bash + ``` sqlite3 < hello.sql ``` @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```sql +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/sql/stage-3/level-3/lesson.md b/lessons/sql/stage-3/level-3/lesson.md index f976f50..34decc4 100644 --- a/lessons/sql/stage-3/level-3/lesson.md +++ b/lessons/sql/stage-3/level-3/lesson.md @@ -51,7 +51,7 @@ Mathematical Problems - Design an algorithm to solve this problem, then implemen ### How to Run 1. **Run the code**: - ```bash + ``` sqlite3 < hello.sql ``` @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```sql +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/sql/stage-3/level-4/lesson.md b/lessons/sql/stage-3/level-4/lesson.md index c86f82c..1dba164 100644 --- a/lessons/sql/stage-3/level-4/lesson.md +++ b/lessons/sql/stage-3/level-4/lesson.md @@ -51,7 +51,7 @@ Text Processing Problems - Design an algorithm to solve this problem, then imple ### How to Run 1. **Run the code**: - ```bash + ``` sqlite3 < hello.sql ``` @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```sql +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/sql/stage-3/level-5/lesson.md b/lessons/sql/stage-3/level-5/lesson.md index 64048a5..3d87e50 100644 --- a/lessons/sql/stage-3/level-5/lesson.md +++ b/lessons/sql/stage-3/level-5/lesson.md @@ -51,7 +51,7 @@ Logic Problems - Design an algorithm to solve this problem, then implement it. ### How to Run 1. **Run the code**: - ```bash + ``` sqlite3 < hello.sql ``` @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```sql +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/sql/stage-3/level-6/lesson.md b/lessons/sql/stage-3/level-6/lesson.md index 3587cc1..762c283 100644 --- a/lessons/sql/stage-3/level-6/lesson.md +++ b/lessons/sql/stage-3/level-6/lesson.md @@ -51,7 +51,7 @@ Search Algorithms - Design an algorithm to solve this problem, then implement it ### How to Run 1. **Run the code**: - ```bash + ``` sqlite3 < hello.sql ``` @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```sql +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/sql/stage-3/level-7/lesson.md b/lessons/sql/stage-3/level-7/lesson.md index 75ede34..8744dcf 100644 --- a/lessons/sql/stage-3/level-7/lesson.md +++ b/lessons/sql/stage-3/level-7/lesson.md @@ -51,7 +51,7 @@ Sorting Algorithms - Design an algorithm to solve this problem, then implement i ### How to Run 1. **Run the code**: - ```bash + ``` sqlite3 < hello.sql ``` @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```sql +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/sql/stage-4/level-1/lesson.md b/lessons/sql/stage-4/level-1/lesson.md index fde022e..80699bb 100644 --- a/lessons/sql/stage-4/level-1/lesson.md +++ b/lessons/sql/stage-4/level-1/lesson.md @@ -30,7 +30,7 @@ Requirements: ### How to Run 1. **Run the code**: - ```bash + ``` sqlite3 < hello.sql ``` diff --git a/lessons/sql/stage-4/level-2/lesson.md b/lessons/sql/stage-4/level-2/lesson.md index 681f31e..468fcd4 100644 --- a/lessons/sql/stage-4/level-2/lesson.md +++ b/lessons/sql/stage-4/level-2/lesson.md @@ -51,7 +51,7 @@ Build a complete Text Analysis Tool application that: ### How to Run 1. **Run the code**: - ```bash + ``` sqlite3 < hello.sql ``` @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```sql +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/sql/stage-4/level-3/lesson.md b/lessons/sql/stage-4/level-3/lesson.md index 8dac3a6..db33bdb 100644 --- a/lessons/sql/stage-4/level-3/lesson.md +++ b/lessons/sql/stage-4/level-3/lesson.md @@ -51,7 +51,7 @@ Build a complete Data Processing application that: ### How to Run 1. **Run the code**: - ```bash + ``` sqlite3 < hello.sql ``` @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```sql +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/sql/stage-4/level-4/lesson.md b/lessons/sql/stage-4/level-4/lesson.md index 0146824..f4f12e8 100644 --- a/lessons/sql/stage-4/level-4/lesson.md +++ b/lessons/sql/stage-4/level-4/lesson.md @@ -51,7 +51,7 @@ Build a complete File Operations application that: ### How to Run 1. **Run the code**: - ```bash + ``` sqlite3 < hello.sql ``` @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```sql +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/sql/stage-4/level-5/lesson.md b/lessons/sql/stage-4/level-5/lesson.md index 97a2821..8f3ade1 100644 --- a/lessons/sql/stage-4/level-5/lesson.md +++ b/lessons/sql/stage-4/level-5/lesson.md @@ -51,7 +51,7 @@ Build a complete API Integration application that: ### How to Run 1. **Run the code**: - ```bash + ``` sqlite3 < hello.sql ``` @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```sql +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/sql/stage-4/level-6/lesson.md b/lessons/sql/stage-4/level-6/lesson.md index 699c428..d60f96a 100644 --- a/lessons/sql/stage-4/level-6/lesson.md +++ b/lessons/sql/stage-4/level-6/lesson.md @@ -51,7 +51,7 @@ Build a complete Database Operations application that: ### How to Run 1. **Run the code**: - ```bash + ``` sqlite3 < hello.sql ``` @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```sql +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/sql/stage-4/level-7/lesson.md b/lessons/sql/stage-4/level-7/lesson.md index 0d60a63..0e2f124 100644 --- a/lessons/sql/stage-4/level-7/lesson.md +++ b/lessons/sql/stage-4/level-7/lesson.md @@ -51,7 +51,7 @@ Build a complete Complete Application application that: ### How to Run 1. **Run the code**: - ```bash + ``` sqlite3 < hello.sql ``` @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```sql +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/sql/stage-5/level-1/lesson.md b/lessons/sql/stage-5/level-1/lesson.md index f63dfed..fc495b7 100644 --- a/lessons/sql/stage-5/level-1/lesson.md +++ b/lessons/sql/stage-5/level-1/lesson.md @@ -30,7 +30,7 @@ You're going to build a complete Sql application. This is a real project that co ### How to Run 1. **Run the code**: - ```bash + ``` sqlite3 < hello.sql ``` diff --git a/lessons/sql/stage-5/level-2/lesson.md b/lessons/sql/stage-5/level-2/lesson.md index 55c2568..076d7b0 100644 --- a/lessons/sql/stage-5/level-2/lesson.md +++ b/lessons/sql/stage-5/level-2/lesson.md @@ -58,7 +58,7 @@ Create a production-ready CLI Tool using SQL with: ### How to Run 1. **Run the code**: - ```bash + ``` sqlite3 < hello.sql ``` diff --git a/lessons/sql/stage-5/level-3/lesson.md b/lessons/sql/stage-5/level-3/lesson.md index 264f305..e005cdd 100644 --- a/lessons/sql/stage-5/level-3/lesson.md +++ b/lessons/sql/stage-5/level-3/lesson.md @@ -58,7 +58,7 @@ Create a production-ready REST API using SQL with: ### How to Run 1. **Run the code**: - ```bash + ``` sqlite3 < hello.sql ``` diff --git a/lessons/sql/stage-5/level-4/lesson.md b/lessons/sql/stage-5/level-4/lesson.md index 1578402..9dd848c 100644 --- a/lessons/sql/stage-5/level-4/lesson.md +++ b/lessons/sql/stage-5/level-4/lesson.md @@ -58,7 +58,7 @@ Create a production-ready Data Visualization using SQL with: ### How to Run 1. **Run the code**: - ```bash + ``` sqlite3 < hello.sql ``` diff --git a/lessons/sql/stage-5/level-5/lesson.md b/lessons/sql/stage-5/level-5/lesson.md index 89dd332..53763bf 100644 --- a/lessons/sql/stage-5/level-5/lesson.md +++ b/lessons/sql/stage-5/level-5/lesson.md @@ -58,7 +58,7 @@ Create a production-ready Automated Testing using SQL with: ### How to Run 1. **Run the code**: - ```bash + ``` sqlite3 < hello.sql ``` diff --git a/lessons/sql/stage-5/level-6/lesson.md b/lessons/sql/stage-5/level-6/lesson.md index 15eeb6d..706078c 100644 --- a/lessons/sql/stage-5/level-6/lesson.md +++ b/lessons/sql/stage-5/level-6/lesson.md @@ -58,7 +58,7 @@ Create a production-ready Performance Optimization using SQL with: ### How to Run 1. **Run the code**: - ```bash + ``` sqlite3 < hello.sql ``` diff --git a/lessons/sql/stage-5/level-7/lesson.md b/lessons/sql/stage-5/level-7/lesson.md index e4fbd22..cbc6735 100644 --- a/lessons/sql/stage-5/level-7/lesson.md +++ b/lessons/sql/stage-5/level-7/lesson.md @@ -58,7 +58,7 @@ Create a production-ready Final Capstone Project using SQL with: ### How to Run 1. **Run the code**: - ```bash + ``` sqlite3 < hello.sql ``` diff --git a/lessons/swift/stage-1/level-1/lesson.md b/lessons/swift/stage-1/level-1/lesson.md index 7fbc228..fc8ce57 100644 --- a/lessons/swift/stage-1/level-1/lesson.md +++ b/lessons/swift/stage-1/level-1/lesson.md @@ -21,21 +21,21 @@ Welcome to Swift! Today, you'll create your first Swift program. Swift is Apple' Copy the following code EXACTLY as shown into a new file called `hello.swift`: -```swift +``` print("Hello, World!") -```swift +``` ### How to Execute -```bash +``` swift hello.swift -```swift +``` Expected output: -```swift +``` Hello, World! -```swift +``` ### Success Checklist @@ -56,81 +56,22 @@ Hello, World! ## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown - -> **NEEDS_AUTHOR:** This lesson needs a complete answer key with code breakdown, execution process explanation, common errors table, and bonus knowledge section. Reference c-c++/stage-1/level-1/lesson.md for the gold standard format. - -### Key Concepts - -- Review the code structure specific to Swift -- Understand the execution flow -- Learn common pitfalls and solutions - -### Next Steps - -Practice the code and experiment with variations! - ---- - -**Congratulations! Keep coding!** - - -### How to Run - -1. Open the code file -2. Review and understand the implementation -3. Execute using: `r` in Vim - +### Solution -### Additional Content - -Understand the key concepts: - -- Review each function -- Understand the flow -- Learn the patterns used - - -### Code Review - -Key functions and their purpose: - -- Main function: Entry point -- Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```swift +``` print("Hello, World!") - ``` -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: +### Explanation -1. **Structure**: The program follows standard swift conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -### Testing Your Solution +### Success Criteria -Try these test cases to verify your code works correctly: +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding +--- -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs +**Great job! You've completed this lesson!** diff --git a/lessons/swift/stage-1/level-2/lesson.md b/lessons/swift/stage-1/level-2/lesson.md index a0b16c3..143aee3 100644 --- a/lessons/swift/stage-1/level-2/lesson.md +++ b/lessons/swift/stage-1/level-2/lesson.md @@ -20,7 +20,7 @@ Now that you know how to run Swift programs, let's learn about variables! Variab Copy the following code EXACTLY as shown into a new file called `variables.swift`: -```swift +``` let name = "Alice" let age = 25 let height = 5.6 @@ -30,22 +30,22 @@ print("Hello, \(name)!") print("You are \(age) years old.") print("Your height is \(height) feet.") print("Student status: \(isStudent)") -```swift +``` ### How to Execute -```bash +``` swift variables.swift -```swift +``` Expected output: -```swift +``` Hello, Alice! You are 25 years old. Your height is 5.6 feet. Student status: true -```swift +``` ### Success Checklist @@ -85,82 +85,30 @@ Remember to check the `VIM_CHEATSHEET.md` in the root directory for basic Vim co ## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown - -> **NEEDS_AUTHOR:** This lesson needs a complete answer key with code breakdown, execution process explanation, common errors table, and bonus knowledge section. Reference c-c++/stage-1/level-1/lesson.md for the gold standard format. - -### Key Concepts - -- Review the code structure specific to Swift -- Understand the execution flow -- Learn common pitfalls and solutions - -### Next Steps - -Practice the code and experiment with variations! - ---- - -**Congratulations! Keep coding!** - - - -### How to Run - -1. Open the code file -2. Review and understand the implementation -3. Execute using: `r` in Vim - - -### Additional Content - -Understand the key concepts: - -- Review each function -- Understand the flow -- Learn the patterns used - - -### Code Review - -Key functions and their purpose: - -- Main function: Entry point -- Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```swift -print("Hello, World!") +### Solution ``` +let name = "Alice" +let age = 25 +let height = 5.6 +let isStudent = true -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: +print("Hello, \(name)!") +print("You are \(age) years old.") +print("Your height is \(height) feet.") +print("Student status: \(isStudent)") +``` -1. **Structure**: The program follows standard swift conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions +### Explanation -### Testing Your Solution +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -Try these test cases to verify your code works correctly: +### Success Criteria -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does -### Tips for Understanding +--- -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs +**Great job! You've completed this lesson!** diff --git a/lessons/swift/stage-1/level-3/lesson.md b/lessons/swift/stage-1/level-3/lesson.md index 9778feb..ed64ce2 100644 --- a/lessons/swift/stage-1/level-3/lesson.md +++ b/lessons/swift/stage-1/level-3/lesson.md @@ -23,7 +23,7 @@ Master arithmetic operations and use the language as your calculator. **Copy the following code EXACTLY as shown below into `main.swift`** -```swift +``` let a = 15 let b = 4 @@ -36,7 +36,7 @@ print("Remainder: \(a) % \(b) = \(a % b)") let x: Double = 15.0 let y: Double = 4.0 print("Precise Division: \(x) / \(y) = \(x / y)") -```swift +``` --- @@ -58,7 +58,7 @@ print("Precise Division: \(x) / \(y) = \(x / y)") ### The Complete Code -```swift +``` let a = 15 let b = 4 @@ -71,7 +71,7 @@ print("Remainder: \(a) % \(b) = \(a % b)") let x: Double = 15.0 let y: Double = 4.0 print("Precise Division: \(x) / \(y) = \(x / y)") -```swift +``` ### What This Code Does @@ -140,40 +140,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```swift -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard swift conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/swift/stage-1/level-4/lesson.md b/lessons/swift/stage-1/level-4/lesson.md index 2167340..c541bde 100644 --- a/lessons/swift/stage-1/level-4/lesson.md +++ b/lessons/swift/stage-1/level-4/lesson.md @@ -23,7 +23,7 @@ Make your programs interactive by reading input from users. **Copy the following code EXACTLY as shown below into `main.swift`** -```swift +``` import Foundation print("Enter your name: ", terminator: "") @@ -35,7 +35,7 @@ let age = Int(readLine() ?? "0") ?? 0 print("Hello, \(name)!") print("You are \(age) years old.") print("Next year you'll be \(age + 1).") -```swift +``` --- @@ -57,7 +57,7 @@ print("Next year you'll be \(age + 1).") ### The Complete Code -```swift +``` import Foundation print("Enter your name: ", terminator: "") @@ -69,7 +69,7 @@ let age = Int(readLine() ?? "0") ?? 0 print("Hello, \(name)!") print("You are \(age) years old.") print("Next year you'll be \(age + 1).") -```swift +``` ### What This Code Does @@ -138,40 +138,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```swift -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard swift conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/swift/stage-1/level-5/lesson.md b/lessons/swift/stage-1/level-5/lesson.md index b2e1e2b..6f0de04 100644 --- a/lessons/swift/stage-1/level-5/lesson.md +++ b/lessons/swift/stage-1/level-5/lesson.md @@ -23,7 +23,7 @@ Add decision-making to your programs with if/else statements. **Copy the following code EXACTLY as shown below into `main.swift`** -```swift +``` import Foundation print("Enter a number: ", terminator: "") @@ -42,7 +42,7 @@ if num % 2 == 0 { } else { print("\(num) is odd") } -```swift +``` --- @@ -64,7 +64,7 @@ if num % 2 == 0 { ### The Complete Code -```swift +``` import Foundation print("Enter a number: ", terminator: "") @@ -83,7 +83,7 @@ if num % 2 == 0 { } else { print("\(num) is odd") } -```swift +``` ### What This Code Does @@ -150,40 +150,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```swift -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard swift conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/swift/stage-1/level-6/lesson.md b/lessons/swift/stage-1/level-6/lesson.md index 6d82a95..6766b25 100644 --- a/lessons/swift/stage-1/level-6/lesson.md +++ b/lessons/swift/stage-1/level-6/lesson.md @@ -23,7 +23,7 @@ Learn to repeat actions efficiently using loops. **Copy the following code EXACTLY as shown below into `main.swift`** -```swift +``` print("Counting 1 to 10:") for i in 1...10 { print("\(i) ", terminator: "") @@ -42,7 +42,7 @@ while count > 0 { count -= 1 } print("Liftoff!") -```swift +``` --- @@ -64,7 +64,7 @@ print("Liftoff!") ### The Complete Code -```swift +``` print("Counting 1 to 10:") for i in 1...10 { print("\(i) ", terminator: "") @@ -83,7 +83,7 @@ while count > 0 { count -= 1 } print("Liftoff!") -```swift +``` ### What This Code Does @@ -149,40 +149,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```swift -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard swift conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/swift/stage-1/level-7/lesson.md b/lessons/swift/stage-1/level-7/lesson.md index 0fc6f94..13810f9 100644 --- a/lessons/swift/stage-1/level-7/lesson.md +++ b/lessons/swift/stage-1/level-7/lesson.md @@ -23,7 +23,7 @@ Organize your code into reusable functions/methods. **Copy the following code EXACTLY as shown below into `main.swift`** -```swift +``` func greet(name: String) { print("Hello, \(name)!") } @@ -45,7 +45,7 @@ print("15 + 7 = \(sum)") let fact = factorial(n: 5) print("5! = \(fact)") -```swift +``` --- @@ -67,7 +67,7 @@ print("5! = \(fact)") ### The Complete Code -```swift +``` func greet(name: String) { print("Hello, \(name)!") } @@ -89,7 +89,7 @@ print("15 + 7 = \(sum)") let fact = factorial(n: 5) print("5! = \(fact)") -```swift +``` ### What This Code Does @@ -158,40 +158,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```swift -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard swift conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/swift/stage-2/level-1/lesson.md b/lessons/swift/stage-2/level-1/lesson.md index 08070b9..5b052ca 100644 --- a/lessons/swift/stage-2/level-1/lesson.md +++ b/lessons/swift/stage-2/level-1/lesson.md @@ -20,13 +20,13 @@ Now that you know the basics, it's time to think like a programmer! You'll take Here's some pseudocode that describes a simple program: -```swift +``` START print "Welcome to the program!" print "This is my first real program" print "I'm learning to code!" END -```swift +``` **Your mission**: Translate this pseudocode into Swift code and save it as `main.swift`. @@ -38,18 +38,18 @@ Hints: ### How to Run -```bash +``` cd ~/.local/share/learn/workspaces/swift/stage-2/level-1 swift main.swift -```swift +``` Expected output: -```swift +``` Welcome to the program! This is my first real program I'm learning to code! -```swift +``` ### Success Checklist @@ -69,53 +69,28 @@ If you're stuck, here's what your code should look like (don't peek until you tr --- -## ANSWER KEY +## ANSWER KEY (No cheating until you've tried!) -```swift -```swift +### Solution -(Fill in based on language-specific syntax) - -```swift - ---- - -## What's Different About Stage 2? - -**Stage 1 (Copying):** Code was provided, you typed it -**Stage 2 (Pseudocode→Code):** Logic is provided, you write the code - -This is a crucial step! You're now writing code from specifications, not just copying. This is how real programming works. - -### Key Concepts +``` +START + print "Welcome to the program!" + print "This is my first real program" + print "I'm learning to code!" +END +``` -- Pseudocode is language-independent - the same pseudocode could translate to many languages -- Your job is to understand the logic and implement it correctly -- Different languages have different syntax, but the logic is the same +### Explanation ---- +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -## Need Help with Vim? +### Success Criteria -Remember to check the `VIM_CHEATSHEET.md` in the root directory for basic Vim commands! +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -
- - -### Additional Content - -Understand the key concepts: - -- Review each function -- Understand the flow -- Learn the patterns used - - -### Code Review - -Key functions and their purpose: - -- Main function: Entry point -- Helper functions: Support logic +**Great job! You've completed this lesson!** diff --git a/lessons/swift/stage-2/level-2/lesson.md b/lessons/swift/stage-2/level-2/lesson.md index 4b33893..1586eed 100644 --- a/lessons/swift/stage-2/level-2/lesson.md +++ b/lessons/swift/stage-2/level-2/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Swift:** -```swift +``` ALGORITHM: Variables in Algorithms BEGIN @@ -39,7 +39,7 @@ BEGIN // Translate step by step into Swift // Test with sample inputs END -```swift +``` **Implementation Steps:** 1. Analyze what the algorithm does @@ -54,14 +54,14 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` swift hello.swift - ```swift + ``` **Expected output:** -```swift +``` Hello, World! -```swift +``` ### How to Approach This @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in Swift: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```swift +``` PSEUDOCODE: READ number IF number > 0 THEN @@ -168,7 +168,7 @@ PSEUDOCODE: ELSE PRINT "Not positive" END IF -```swift +``` This becomes structured Swift code following the language syntax. @@ -211,40 +211,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```swift -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard swift conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/swift/stage-2/level-3/lesson.md b/lessons/swift/stage-2/level-3/lesson.md index 08e5c97..dcc8cbd 100644 --- a/lessons/swift/stage-2/level-3/lesson.md +++ b/lessons/swift/stage-2/level-3/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Swift:** -```swift +``` ALGORITHM: Mathematical Algorithms BEGIN @@ -39,7 +39,7 @@ BEGIN // Translate step by step into Swift // Test with sample inputs END -```swift +``` **Implementation Steps:** 1. Analyze what the algorithm does @@ -54,14 +54,14 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` swift hello.swift - ```swift + ``` **Expected output:** -```swift +``` Hello, World! -```swift +``` ### How to Approach This @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in Swift: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```swift +``` PSEUDOCODE: READ number IF number > 0 THEN @@ -168,7 +168,7 @@ PSEUDOCODE: ELSE PRINT "Not positive" END IF -```swift +``` This becomes structured Swift code following the language syntax. @@ -211,40 +211,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```swift -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard swift conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/swift/stage-2/level-4/lesson.md b/lessons/swift/stage-2/level-4/lesson.md index a123229..26f13d9 100644 --- a/lessons/swift/stage-2/level-4/lesson.md +++ b/lessons/swift/stage-2/level-4/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Swift:** -```swift +``` ALGORITHM: Input/Output Algorithms BEGIN @@ -39,7 +39,7 @@ BEGIN // Translate step by step into Swift // Test with sample inputs END -```swift +``` **Implementation Steps:** 1. Analyze what the algorithm does @@ -54,14 +54,14 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` swift hello.swift - ```swift + ``` **Expected output:** -```swift +``` Hello, World! -```swift +``` ### How to Approach This @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in Swift: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```swift +``` PSEUDOCODE: READ number IF number > 0 THEN @@ -168,7 +168,7 @@ PSEUDOCODE: ELSE PRINT "Not positive" END IF -```swift +``` This becomes structured Swift code following the language syntax. @@ -211,40 +211,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```swift -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard swift conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/swift/stage-2/level-5/lesson.md b/lessons/swift/stage-2/level-5/lesson.md index 2a8f72d..4ae1d2c 100644 --- a/lessons/swift/stage-2/level-5/lesson.md +++ b/lessons/swift/stage-2/level-5/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Swift:** -```swift +``` ALGORITHM: Decision Algorithms BEGIN @@ -39,7 +39,7 @@ BEGIN // Translate step by step into Swift // Test with sample inputs END -```swift +``` **Implementation Steps:** 1. Analyze what the algorithm does @@ -54,14 +54,14 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` swift hello.swift - ```swift + ``` **Expected output:** -```swift +``` Hello, World! -```swift +``` ### How to Approach This @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in Swift: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```swift +``` PSEUDOCODE: READ number IF number > 0 THEN @@ -168,7 +168,7 @@ PSEUDOCODE: ELSE PRINT "Not positive" END IF -```swift +``` This becomes structured Swift code following the language syntax. @@ -211,40 +211,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```swift -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard swift conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/swift/stage-2/level-6/lesson.md b/lessons/swift/stage-2/level-6/lesson.md index bfebec8..c0828ef 100644 --- a/lessons/swift/stage-2/level-6/lesson.md +++ b/lessons/swift/stage-2/level-6/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Swift:** -```swift +``` ALGORITHM: Loop Algorithms BEGIN @@ -39,7 +39,7 @@ BEGIN // Translate step by step into Swift // Test with sample inputs END -```swift +``` **Implementation Steps:** 1. Analyze what the algorithm does @@ -54,14 +54,14 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` swift hello.swift - ```swift + ``` **Expected output:** -```swift +``` Hello, World! -```swift +``` ### How to Approach This @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in Swift: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```swift +``` PSEUDOCODE: READ number IF number > 0 THEN @@ -168,7 +168,7 @@ PSEUDOCODE: ELSE PRINT "Not positive" END IF -```swift +``` This becomes structured Swift code following the language syntax. @@ -211,40 +211,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```swift -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard swift conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/swift/stage-2/level-7/lesson.md b/lessons/swift/stage-2/level-7/lesson.md index 8c9c029..35c7c7b 100644 --- a/lessons/swift/stage-2/level-7/lesson.md +++ b/lessons/swift/stage-2/level-7/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Swift:** -```swift +``` ALGORITHM: Function Design BEGIN @@ -39,7 +39,7 @@ BEGIN // Translate step by step into Swift // Test with sample inputs END -```swift +``` **Implementation Steps:** 1. Analyze what the algorithm does @@ -54,14 +54,14 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` swift hello.swift - ```swift + ``` **Expected output:** -```swift +``` Hello, World! -```swift +``` ### How to Approach This @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in Swift: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```swift +``` PSEUDOCODE: READ number IF number > 0 THEN @@ -168,7 +168,7 @@ PSEUDOCODE: ELSE PRINT "Not positive" END IF -```swift +``` This becomes structured Swift code following the language syntax. @@ -211,40 +211,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```swift -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard swift conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/swift/stage-3/level-1/lesson.md b/lessons/swift/stage-3/level-1/lesson.md index 9f9e7ba..b6c9578 100644 --- a/lessons/swift/stage-3/level-1/lesson.md +++ b/lessons/swift/stage-3/level-1/lesson.md @@ -22,13 +22,13 @@ You're now ready for Stage 3! This is where you start thinking like a real progr Step 1: Write the pseudocode first -```swift +``` What should happen: 1. Print "Hello, [name]" Write your pseudocode in plain English below: (Your pseudocode here) -```swift +``` Step 2: Implement your pseudocode in Swift @@ -38,14 +38,14 @@ Create `main.swift.swift` with your solution. ### How to Run 1. **Run the code**: - ```bash + ``` swift hello.swift - ```swift + ``` **Expected output:** -```swift +``` Hello, World! -```swift +``` ### Success Checklist @@ -87,75 +87,26 @@ Check the `VIM_CHEATSHEET.md` for basic Vim commands! ## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown - -> **NEEDS_AUTHOR:** This lesson needs a complete answer key with code breakdown, execution process explanation, common errors table, and bonus knowledge section. Reference c-c++/stage-1/level-1/lesson.md for the gold standard format. - -### Key Concepts - -- Review the code structure specific to Swift -- Understand the execution flow -- Learn common pitfalls and solutions - -### Next Steps - -Practice the code and experiment with variations! - ---- - -**Congratulations! Keep coding!** - - - -### Additional Content - -Understand the key concepts: - -- Review each function -- Understand the flow -- Learn the patterns used - - -### Code Review - -Key functions and their purpose: - -- Main function: Entry point -- Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```swift -print("Hello, World!") +### Solution ``` +What should happen: +1. Print "Hello, [name]" -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: +Write your pseudocode in plain English below: +(Your pseudocode here) +``` -1. **Structure**: The program follows standard swift conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions +### Explanation -### Testing Your Solution +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -Try these test cases to verify your code works correctly: +### Success Criteria -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does -### Tips for Understanding +--- -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs +**Great job! You've completed this lesson!** diff --git a/lessons/swift/stage-3/level-2/lesson.md b/lessons/swift/stage-3/level-2/lesson.md index 0c19aa4..5255c75 100644 --- a/lessons/swift/stage-3/level-2/lesson.md +++ b/lessons/swift/stage-3/level-2/lesson.md @@ -51,14 +51,14 @@ Data Structure Planning - Design an algorithm to solve this problem, then implem ### How to Run 1. **Run the code**: - ```bash + ``` swift hello.swift - ```swift + ``` **Expected output:** -```swift +``` Hello, World! -```swift +``` ### How to Approach This @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```swift +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -169,7 +169,7 @@ BEGIN - Step 3 4. Display results END -```swift +``` Then translate this directly to Swift code. @@ -212,40 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```swift -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard swift conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/swift/stage-3/level-3/lesson.md b/lessons/swift/stage-3/level-3/lesson.md index 26ea3a2..0ab8d48 100644 --- a/lessons/swift/stage-3/level-3/lesson.md +++ b/lessons/swift/stage-3/level-3/lesson.md @@ -51,14 +51,14 @@ Mathematical Problems - Design an algorithm to solve this problem, then implemen ### How to Run 1. **Run the code**: - ```bash + ``` swift hello.swift - ```swift + ``` **Expected output:** -```swift +``` Hello, World! -```swift +``` ### How to Approach This @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```swift +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -169,7 +169,7 @@ BEGIN - Step 3 4. Display results END -```swift +``` Then translate this directly to Swift code. @@ -212,40 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```swift -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard swift conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/swift/stage-3/level-4/lesson.md b/lessons/swift/stage-3/level-4/lesson.md index 3bf5536..6281744 100644 --- a/lessons/swift/stage-3/level-4/lesson.md +++ b/lessons/swift/stage-3/level-4/lesson.md @@ -51,14 +51,14 @@ Text Processing Problems - Design an algorithm to solve this problem, then imple ### How to Run 1. **Run the code**: - ```bash + ``` swift hello.swift - ```swift + ``` **Expected output:** -```swift +``` Hello, World! -```swift +``` ### How to Approach This @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```swift +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -169,7 +169,7 @@ BEGIN - Step 3 4. Display results END -```swift +``` Then translate this directly to Swift code. @@ -212,40 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```swift -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard swift conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/swift/stage-3/level-5/lesson.md b/lessons/swift/stage-3/level-5/lesson.md index 8c567f1..c8fde7e 100644 --- a/lessons/swift/stage-3/level-5/lesson.md +++ b/lessons/swift/stage-3/level-5/lesson.md @@ -51,14 +51,14 @@ Logic Problems - Design an algorithm to solve this problem, then implement it. ### How to Run 1. **Run the code**: - ```bash + ``` swift hello.swift - ```swift + ``` **Expected output:** -```swift +``` Hello, World! -```swift +``` ### How to Approach This @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```swift +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -169,7 +169,7 @@ BEGIN - Step 3 4. Display results END -```swift +``` Then translate this directly to Swift code. @@ -212,40 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```swift -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard swift conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/swift/stage-3/level-6/lesson.md b/lessons/swift/stage-3/level-6/lesson.md index ae065f7..5760c74 100644 --- a/lessons/swift/stage-3/level-6/lesson.md +++ b/lessons/swift/stage-3/level-6/lesson.md @@ -51,14 +51,14 @@ Search Algorithms - Design an algorithm to solve this problem, then implement it ### How to Run 1. **Run the code**: - ```bash + ``` swift hello.swift - ```swift + ``` **Expected output:** -```swift +``` Hello, World! -```swift +``` ### How to Approach This @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```swift +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -169,7 +169,7 @@ BEGIN - Step 3 4. Display results END -```swift +``` Then translate this directly to Swift code. @@ -212,40 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```swift -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard swift conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/swift/stage-3/level-7/lesson.md b/lessons/swift/stage-3/level-7/lesson.md index 5568612..cffbd78 100644 --- a/lessons/swift/stage-3/level-7/lesson.md +++ b/lessons/swift/stage-3/level-7/lesson.md @@ -51,14 +51,14 @@ Sorting Algorithms - Design an algorithm to solve this problem, then implement i ### How to Run 1. **Run the code**: - ```bash + ``` swift hello.swift - ```swift + ``` **Expected output:** -```swift +``` Hello, World! -```swift +``` ### How to Approach This @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```swift +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -169,7 +169,7 @@ BEGIN - Step 3 4. Display results END -```swift +``` Then translate this directly to Swift code. @@ -212,40 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```swift -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard swift conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/swift/stage-4/level-1/lesson.md b/lessons/swift/stage-4/level-1/lesson.md index cc2f1a1..8d823ae 100644 --- a/lessons/swift/stage-4/level-1/lesson.md +++ b/lessons/swift/stage-4/level-1/lesson.md @@ -30,14 +30,14 @@ Requirements: ### How to Run 1. **Run the code**: - ```bash + ``` swift hello.swift - ```swift + ``` **Expected output:** -```swift +``` Hello, World! -```swift +``` ### How to Approach This @@ -115,40 +115,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```swift -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard swift conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/swift/stage-4/level-2/lesson.md b/lessons/swift/stage-4/level-2/lesson.md index 6fd87b0..7a9cfbd 100644 --- a/lessons/swift/stage-4/level-2/lesson.md +++ b/lessons/swift/stage-4/level-2/lesson.md @@ -51,14 +51,14 @@ Build a complete Text Analysis Tool application that: ### How to Run 1. **Run the code**: - ```bash + ``` swift hello.swift - ```swift + ``` **Expected output:** -```swift +``` Hello, World! -```swift +``` ### How to Approach This @@ -158,13 +158,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```swift +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```swift +``` Build incrementally - get one feature working before adding the next. @@ -207,40 +207,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```swift -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard swift conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/swift/stage-4/level-3/lesson.md b/lessons/swift/stage-4/level-3/lesson.md index df4691b..3dca936 100644 --- a/lessons/swift/stage-4/level-3/lesson.md +++ b/lessons/swift/stage-4/level-3/lesson.md @@ -51,14 +51,14 @@ Build a complete Data Processing application that: ### How to Run 1. **Run the code**: - ```bash + ``` swift hello.swift - ```swift + ``` **Expected output:** -```swift +``` Hello, World! -```swift +``` ### How to Approach This @@ -158,13 +158,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```swift +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```swift +``` Build incrementally - get one feature working before adding the next. @@ -207,40 +207,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```swift -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard swift conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/swift/stage-4/level-4/lesson.md b/lessons/swift/stage-4/level-4/lesson.md index 89a4f31..565c3a9 100644 --- a/lessons/swift/stage-4/level-4/lesson.md +++ b/lessons/swift/stage-4/level-4/lesson.md @@ -51,14 +51,14 @@ Build a complete File Operations application that: ### How to Run 1. **Run the code**: - ```bash + ``` swift hello.swift - ```swift + ``` **Expected output:** -```swift +``` Hello, World! -```swift +``` ### How to Approach This @@ -158,13 +158,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```swift +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```swift +``` Build incrementally - get one feature working before adding the next. @@ -207,40 +207,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```swift -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard swift conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/swift/stage-4/level-5/lesson.md b/lessons/swift/stage-4/level-5/lesson.md index 125ee63..022a8c5 100644 --- a/lessons/swift/stage-4/level-5/lesson.md +++ b/lessons/swift/stage-4/level-5/lesson.md @@ -51,14 +51,14 @@ Build a complete API Integration application that: ### How to Run 1. **Run the code**: - ```bash + ``` swift hello.swift - ```swift + ``` **Expected output:** -```swift +``` Hello, World! -```swift +``` ### How to Approach This @@ -158,13 +158,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```swift +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```swift +``` Build incrementally - get one feature working before adding the next. @@ -207,40 +207,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```swift -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard swift conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/swift/stage-4/level-6/lesson.md b/lessons/swift/stage-4/level-6/lesson.md index 71adbcb..2addafa 100644 --- a/lessons/swift/stage-4/level-6/lesson.md +++ b/lessons/swift/stage-4/level-6/lesson.md @@ -51,14 +51,14 @@ Build a complete Database Operations application that: ### How to Run 1. **Run the code**: - ```bash + ``` swift hello.swift - ```swift + ``` **Expected output:** -```swift +``` Hello, World! -```swift +``` ### How to Approach This @@ -158,13 +158,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```swift +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```swift +``` Build incrementally - get one feature working before adding the next. @@ -207,40 +207,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```swift -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard swift conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/swift/stage-4/level-7/lesson.md b/lessons/swift/stage-4/level-7/lesson.md index 62f0ca7..5a57ab7 100644 --- a/lessons/swift/stage-4/level-7/lesson.md +++ b/lessons/swift/stage-4/level-7/lesson.md @@ -51,14 +51,14 @@ Build a complete Complete Application application that: ### How to Run 1. **Run the code**: - ```bash + ``` swift hello.swift - ```swift + ``` **Expected output:** -```swift +``` Hello, World! -```swift +``` ### How to Approach This @@ -158,13 +158,13 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```swift +``` // Setup and initialization // Main program loop or flow // Helper functions // Error handlers // Testing/verification -```swift +``` Build incrementally - get one feature working before adding the next. @@ -207,40 +207,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```swift -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard swift conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/swift/stage-5/level-1/lesson.md b/lessons/swift/stage-5/level-1/lesson.md index fed1aef..82a76cd 100644 --- a/lessons/swift/stage-5/level-1/lesson.md +++ b/lessons/swift/stage-5/level-1/lesson.md @@ -30,14 +30,14 @@ You're going to build a complete Swift application. This is a real project that ### How to Run 1. **Run the code**: - ```bash + ``` swift hello.swift - ```swift + ``` **Expected output:** -```swift +``` Hello, World! -```swift +``` ### Project Requirements @@ -156,40 +156,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```swift -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard swift conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/swift/stage-5/level-2/lesson.md b/lessons/swift/stage-5/level-2/lesson.md index 2bf648f..970ff18 100644 --- a/lessons/swift/stage-5/level-2/lesson.md +++ b/lessons/swift/stage-5/level-2/lesson.md @@ -58,14 +58,14 @@ Create a production-ready CLI Tool using Swift with: ### How to Run 1. **Run the code**: - ```bash + ``` swift hello.swift - ```swift + ``` **Expected output:** -```swift +``` Hello, World! -```swift +``` ### How to Approach This @@ -222,40 +222,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```swift -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard swift conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/swift/stage-5/level-3/lesson.md b/lessons/swift/stage-5/level-3/lesson.md index 6d9efd2..8911581 100644 --- a/lessons/swift/stage-5/level-3/lesson.md +++ b/lessons/swift/stage-5/level-3/lesson.md @@ -58,14 +58,14 @@ Create a production-ready REST API using Swift with: ### How to Run 1. **Run the code**: - ```bash + ``` swift hello.swift - ```swift + ``` **Expected output:** -```swift +``` Hello, World! -```swift +``` ### How to Approach This @@ -222,40 +222,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```swift -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard swift conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/swift/stage-5/level-4/lesson.md b/lessons/swift/stage-5/level-4/lesson.md index c1d6661..7044100 100644 --- a/lessons/swift/stage-5/level-4/lesson.md +++ b/lessons/swift/stage-5/level-4/lesson.md @@ -58,14 +58,14 @@ Create a production-ready Data Visualization using Swift with: ### How to Run 1. **Run the code**: - ```bash + ``` swift hello.swift - ```swift + ``` **Expected output:** -```swift +``` Hello, World! -```swift +``` ### How to Approach This @@ -222,40 +222,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```swift -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard swift conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/swift/stage-5/level-5/lesson.md b/lessons/swift/stage-5/level-5/lesson.md index f4850e5..16b6e5b 100644 --- a/lessons/swift/stage-5/level-5/lesson.md +++ b/lessons/swift/stage-5/level-5/lesson.md @@ -58,14 +58,14 @@ Create a production-ready Automated Testing using Swift with: ### How to Run 1. **Run the code**: - ```bash + ``` swift hello.swift - ```swift + ``` **Expected output:** -```swift +``` Hello, World! -```swift +``` ### How to Approach This @@ -222,40 +222,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```swift -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard swift conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/swift/stage-5/level-6/lesson.md b/lessons/swift/stage-5/level-6/lesson.md index 97ef436..82072a2 100644 --- a/lessons/swift/stage-5/level-6/lesson.md +++ b/lessons/swift/stage-5/level-6/lesson.md @@ -58,14 +58,14 @@ Create a production-ready Performance Optimization using Swift with: ### How to Run 1. **Run the code**: - ```bash + ``` swift hello.swift - ```swift + ``` **Expected output:** -```swift +``` Hello, World! -```swift +``` ### How to Approach This @@ -222,40 +222,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```swift -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard swift conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/swift/stage-5/level-7/lesson.md b/lessons/swift/stage-5/level-7/lesson.md index 6c3fdad..19f7eaf 100644 --- a/lessons/swift/stage-5/level-7/lesson.md +++ b/lessons/swift/stage-5/level-7/lesson.md @@ -58,14 +58,14 @@ Create a production-ready Final Capstone Project using Swift with: ### How to Run 1. **Run the code**: - ```bash + ``` swift hello.swift - ```swift + ``` **Expected output:** -```swift +``` Hello, World! -```swift +``` ### How to Approach This @@ -222,40 +222,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```swift -print("Hello, World!") - -``` - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard swift conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/typescript/stage-1/level-1/lesson.md b/lessons/typescript/stage-1/level-1/lesson.md index 7941f3a..900ab6e 100644 --- a/lessons/typescript/stage-1/level-1/lesson.md +++ b/lessons/typescript/stage-1/level-1/lesson.md @@ -21,19 +21,19 @@ Welcome to TypeScript! Today, you'll create your first TypeScript program. TypeS Copy the following code EXACTLY as shown into a new file called `hello.ts`: -```typescript +``` console.log("Hello, World!"); ```type ### How to Execute -```bash +``` ts-node hello.ts ```type Expected output: -```typescript +``` Hello, World! ```type @@ -56,81 +56,22 @@ Hello, World! ## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -> **NEEDS_AUTHOR:** This lesson needs a complete answer key with code breakdown, execution process explanation, common errors table, and bonus knowledge section. Reference c-c++/stage-1/level-1/lesson.md for the gold standard format. - -### Key Concepts - -- Review the code structure specific to Typescript -- Understand the execution flow -- Learn common pitfalls and solutions - -### Next Steps - -Practice the code and experiment with variations! - ---- - -**Congratulations! Keep coding!** - - -### How to Run - -1. Open the code file -2. Review and understand the implementation -3. Execute using: `r` in Vim - - -### Additional Content - -Understand the key concepts: - -- Review each function -- Understand the flow -- Learn the patterns used - - -### Code Review - -Key functions and their purpose: - -- Main function: Entry point -- Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```ts +``` console.log("Hello, World!"); +``` -```ts - -### Code Breakdown +### Explanation -This solution demonstrates the key concepts from this lesson: +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -1. **Structure**: The program follows standard typescript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions +### Success Criteria -### Testing Your Solution +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding +--- -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs +**Great job! You've completed this lesson!** diff --git a/lessons/typescript/stage-1/level-2/lesson.md b/lessons/typescript/stage-1/level-2/lesson.md index 0360c2c..f4dd232 100644 --- a/lessons/typescript/stage-1/level-2/lesson.md +++ b/lessons/typescript/stage-1/level-2/lesson.md @@ -20,7 +20,7 @@ Now that you know how to run Typescript programs, let's learn about variables! V Copy the following code EXACTLY as shown into a new file called `variables.ts`: -```ts +``` const name: string = "Alice"; const age: number = 25; const height: number = 5.6; @@ -34,13 +34,13 @@ console.log(`Student status: ${isStudent}`); ### How to Execute -```bash +``` ts-node variables.ts ```type Expected output: -```typescript +``` Hello, Alice! You are 25 years old. Your height is 5.6 feet. @@ -85,82 +85,30 @@ Remember to check the `VIM_CHEATSHEET.md` in the root directory for basic Vim co ## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -> **NEEDS_AUTHOR:** This lesson needs a complete answer key with code breakdown, execution process explanation, common errors table, and bonus knowledge section. Reference c-c++/stage-1/level-1/lesson.md for the gold standard format. - -### Key Concepts - -- Review the code structure specific to Typescript -- Understand the execution flow -- Learn common pitfalls and solutions - -### Next Steps - -Practice the code and experiment with variations! - ---- - -**Congratulations! Keep coding!** - - - -### How to Run - -1. Open the code file -2. Review and understand the implementation -3. Execute using: `r` in Vim - - -### Additional Content - -Understand the key concepts: - -- Review each function -- Understand the flow -- Learn the patterns used - - -### Code Review - -Key functions and their purpose: - -- Main function: Entry point -- Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```ts -console.log("Hello, World!"); - -```ts - -### Code Breakdown +``` +const name: string = "Alice"; +const age: number = 25; +const height: number = 5.6; +const isStudent: boolean = true; -This solution demonstrates the key concepts from this lesson: +console.log(`Hello, ${name}!`); +console.log(`You are ${age} years old.`); +console.log(`Your height is ${height} feet.`); +console.log(`Student status: ${isStudent}`); +``` -1. **Structure**: The program follows standard typescript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions +### Explanation -### Testing Your Solution +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -Try these test cases to verify your code works correctly: +### Success Criteria -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does -### Tips for Understanding +--- -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs +**Great job! You've completed this lesson!** diff --git a/lessons/typescript/stage-1/level-3/lesson.md b/lessons/typescript/stage-1/level-3/lesson.md index 44a1a68..7de58d1 100644 --- a/lessons/typescript/stage-1/level-3/lesson.md +++ b/lessons/typescript/stage-1/level-3/lesson.md @@ -23,7 +23,7 @@ Master arithmetic operations and use the language as your calculator. **Copy the following code EXACTLY as shown below into `main.ts`** -```typescript +``` const a: number = 15; const b: number = 4; @@ -58,7 +58,7 @@ console.log(`Precise Division: ${x} / ${y} = ${x / y}`); ### The Complete Code -```typescript +``` const a: number = 15; const b: number = 4; @@ -140,40 +140,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```ts -console.log("Hello, World!"); - -```ts - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard typescript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/typescript/stage-1/level-4/lesson.md b/lessons/typescript/stage-1/level-4/lesson.md index 982f1f7..677d929 100644 --- a/lessons/typescript/stage-1/level-4/lesson.md +++ b/lessons/typescript/stage-1/level-4/lesson.md @@ -23,7 +23,7 @@ Make your programs interactive by reading input from users. **Copy the following code EXACTLY as shown below into `main.ts`** -```typescript +``` import * as readline from 'readline'; const rl = readline.createInterface({ @@ -34,11 +34,11 @@ const rl = readline.createInterface({ rl.question('Enter your name: ', (name: string) => { rl.question('Enter your age: ', (ageStr: string) => { const age: number = parseInt(ageStr); - + console.log(`Hello, ${name}!`); console.log(`You are ${age} years old.`); console.log(`Next year you'll be ${age + 1}.`); - + rl.close(); }); }); @@ -64,7 +64,7 @@ rl.question('Enter your name: ', (name: string) => { ### The Complete Code -```typescript +``` import * as readline from 'readline'; const rl = readline.createInterface({ @@ -75,11 +75,11 @@ const rl = readline.createInterface({ rl.question('Enter your name: ', (name: string) => { rl.question('Enter your age: ', (ageStr: string) => { const age: number = parseInt(ageStr); - + console.log(`Hello, ${name}!`); console.log(`You are ${age} years old.`); console.log(`Next year you'll be ${age + 1}.`); - + rl.close(); }); }); @@ -152,40 +152,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```ts -console.log("Hello, World!"); - -```ts - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard typescript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/typescript/stage-1/level-5/lesson.md b/lessons/typescript/stage-1/level-5/lesson.md index 9d21dea..b752696 100644 --- a/lessons/typescript/stage-1/level-5/lesson.md +++ b/lessons/typescript/stage-1/level-5/lesson.md @@ -23,7 +23,7 @@ Add decision-making to your programs with if/else statements. **Copy the following code EXACTLY as shown below into `main.ts`** -```typescript +``` import * as readline from 'readline'; const rl = readline.createInterface({ @@ -33,7 +33,7 @@ const rl = readline.createInterface({ rl.question('Enter a number: ', (input: string) => { const num: number = parseInt(input); - + if (num > 0) { console.log(`${num} is positive`); } else if (num < 0) { @@ -41,13 +41,13 @@ rl.question('Enter a number: ', (input: string) => { } else { console.log('The number is zero'); } - + if (num % 2 === 0) { console.log(`${num} is even`); } else { console.log(`${num} is odd`); } - + rl.close(); }); ```type @@ -72,7 +72,7 @@ rl.question('Enter a number: ', (input: string) => { ### The Complete Code -```typescript +``` import * as readline from 'readline'; const rl = readline.createInterface({ @@ -82,7 +82,7 @@ const rl = readline.createInterface({ rl.question('Enter a number: ', (input: string) => { const num: number = parseInt(input); - + if (num > 0) { console.log(`${num} is positive`); } else if (num < 0) { @@ -90,13 +90,13 @@ rl.question('Enter a number: ', (input: string) => { } else { console.log('The number is zero'); } - + if (num % 2 === 0) { console.log(`${num} is even`); } else { console.log(`${num} is odd`); } - + rl.close(); }); ```type @@ -166,40 +166,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```ts -console.log("Hello, World!"); - -```ts - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard typescript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/typescript/stage-1/level-6/lesson.md b/lessons/typescript/stage-1/level-6/lesson.md index 6aaa49f..f98f4bb 100644 --- a/lessons/typescript/stage-1/level-6/lesson.md +++ b/lessons/typescript/stage-1/level-6/lesson.md @@ -23,7 +23,7 @@ Learn to repeat actions efficiently using loops. **Copy the following code EXACTLY as shown below into `main.ts`** -```typescript +``` console.log('Counting 1 to 10:'); for (let i: number = 1; i <= 10; i++) { process.stdout.write(`${i} `); @@ -64,7 +64,7 @@ console.log('Liftoff!'); ### The Complete Code -```typescript +``` console.log('Counting 1 to 10:'); for (let i: number = 1; i <= 10; i++) { process.stdout.write(`${i} `); @@ -149,40 +149,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```ts -console.log("Hello, World!"); - -```ts - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard typescript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/typescript/stage-1/level-7/lesson.md b/lessons/typescript/stage-1/level-7/lesson.md index cb8b746..ce1bf4e 100644 --- a/lessons/typescript/stage-1/level-7/lesson.md +++ b/lessons/typescript/stage-1/level-7/lesson.md @@ -23,7 +23,7 @@ Organize your code into reusable functions/methods. **Copy the following code EXACTLY as shown below into `main.ts`** -```typescript +``` function greet(name: string): void { console.log(`Hello, ${name}!`); } @@ -67,7 +67,7 @@ console.log(`5! = ${fact}`); ### The Complete Code -```typescript +``` function greet(name: string): void { console.log(`Hello, ${name}!`); } @@ -158,40 +158,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```ts -console.log("Hello, World!"); - -```ts - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard typescript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/typescript/stage-2/level-1/lesson.md b/lessons/typescript/stage-2/level-1/lesson.md index 70d39bb..5052936 100644 --- a/lessons/typescript/stage-2/level-1/lesson.md +++ b/lessons/typescript/stage-2/level-1/lesson.md @@ -20,7 +20,7 @@ Now that you know the basics, it's time to think like a programmer! You'll take Here's some pseudocode that describes a simple program: -```typescript +``` START print "Welcome to the program!" print "This is my first real program" @@ -38,14 +38,14 @@ Hints: ### How to Run -```bash +``` cd ~/.local/share/learn/workspaces/typescript/stage-2/level-1 ts-node main.ts ```type Expected output: -```typescript +``` Welcome to the program! This is my first real program I'm learning to code! @@ -69,53 +69,28 @@ If you're stuck, here's what your code should look like (don't peek until you tr --- -## ANSWER KEY +## ANSWER KEY (No cheating until you've tried!) -```ts -```type - -(Fill in based on language-specific syntax) - -```typescript - ---- - -## What's Different About Stage 2? +### Solution -**Stage 1 (Copying):** Code was provided, you typed it -**Stage 2 (Pseudocode→Code):** Logic is provided, you write the code - -This is a crucial step! You're now writing code from specifications, not just copying. This is how real programming works. - -### Key Concepts +``` +START + print "Welcome to the program!" + print "This is my first real program" + print "I'm learning to code!" +END +``` -- Pseudocode is language-independent - the same pseudocode could translate to many languages -- Your job is to understand the logic and implement it correctly -- Different languages have different syntax, but the logic is the same +### Explanation ---- +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -## Need Help with Vim? +### Success Criteria -Remember to check the `VIM_CHEATSHEET.md` in the root directory for basic Vim commands! +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -
- - -### Additional Content - -Understand the key concepts: - -- Review each function -- Understand the flow -- Learn the patterns used - - -### Code Review - -Key functions and their purpose: - -- Main function: Entry point -- Helper functions: Support logic +**Great job! You've completed this lesson!** diff --git a/lessons/typescript/stage-2/level-2/lesson.md b/lessons/typescript/stage-2/level-2/lesson.md index 32c33c0..eb54f6b 100644 --- a/lessons/typescript/stage-2/level-2/lesson.md +++ b/lessons/typescript/stage-2/level-2/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Typescript:** -```typescript +``` ALGORITHM: Variables in Algorithms BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` ts-node hello.ts ```type @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in Typescript 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```typescript +``` PSEUDOCODE: READ number IF number > 0 THEN @@ -211,40 +211,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```ts -console.log("Hello, World!"); - -```ts - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard typescript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/typescript/stage-2/level-3/lesson.md b/lessons/typescript/stage-2/level-3/lesson.md index 62cbe8f..2d0fddd 100644 --- a/lessons/typescript/stage-2/level-3/lesson.md +++ b/lessons/typescript/stage-2/level-3/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Typescript:** -```typescript +``` ALGORITHM: Mathematical Algorithms BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` ts-node hello.ts ```type @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in Typescript 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```typescript +``` PSEUDOCODE: READ number IF number > 0 THEN @@ -211,40 +211,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```ts -console.log("Hello, World!"); - -```ts - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard typescript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/typescript/stage-2/level-4/lesson.md b/lessons/typescript/stage-2/level-4/lesson.md index 18da62c..cbf7e3b 100644 --- a/lessons/typescript/stage-2/level-4/lesson.md +++ b/lessons/typescript/stage-2/level-4/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Typescript:** -```typescript +``` ALGORITHM: Input/Output Algorithms BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` ts-node hello.ts ```type @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in Typescript 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```typescript +``` PSEUDOCODE: READ number IF number > 0 THEN @@ -211,40 +211,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```ts -console.log("Hello, World!"); - -```ts - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard typescript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/typescript/stage-2/level-5/lesson.md b/lessons/typescript/stage-2/level-5/lesson.md index d5e3ee2..4e7f878 100644 --- a/lessons/typescript/stage-2/level-5/lesson.md +++ b/lessons/typescript/stage-2/level-5/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Typescript:** -```typescript +``` ALGORITHM: Decision Algorithms BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` ts-node hello.ts ```type @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in Typescript 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```typescript +``` PSEUDOCODE: READ number IF number > 0 THEN @@ -211,40 +211,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```ts -console.log("Hello, World!"); - -```ts - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard typescript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/typescript/stage-2/level-6/lesson.md b/lessons/typescript/stage-2/level-6/lesson.md index 669d34a..a18085a 100644 --- a/lessons/typescript/stage-2/level-6/lesson.md +++ b/lessons/typescript/stage-2/level-6/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Typescript:** -```typescript +``` ALGORITHM: Loop Algorithms BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` ts-node hello.ts ```type @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in Typescript 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```typescript +``` PSEUDOCODE: READ number IF number > 0 THEN @@ -211,40 +211,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```ts -console.log("Hello, World!"); - -```ts - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard typescript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/typescript/stage-2/level-7/lesson.md b/lessons/typescript/stage-2/level-7/lesson.md index 67ea65c..d068bce 100644 --- a/lessons/typescript/stage-2/level-7/lesson.md +++ b/lessons/typescript/stage-2/level-7/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Typescript:** -```typescript +``` ALGORITHM: Function Design BEGIN @@ -54,7 +54,7 @@ END ### How to Run 1. **Run the code**: - ```bash + ``` ts-node hello.ts ```type @@ -160,7 +160,7 @@ The key is understanding what each pseudocode statement represents in Typescript 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```typescript +``` PSEUDOCODE: READ number IF number > 0 THEN @@ -211,40 +211,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```ts -console.log("Hello, World!"); - -```ts - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard typescript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/typescript/stage-3/level-1/lesson.md b/lessons/typescript/stage-3/level-1/lesson.md index ce1c814..abfa85e 100644 --- a/lessons/typescript/stage-3/level-1/lesson.md +++ b/lessons/typescript/stage-3/level-1/lesson.md @@ -22,7 +22,7 @@ You're now ready for Stage 3! This is where you start thinking like a real progr Step 1: Write the pseudocode first -```typescript +``` What should happen: 1. Print "Hello, [name]" @@ -38,7 +38,7 @@ Create `main.typescript.typescript` with your solution. ### How to Run 1. **Run the code**: - ```bash + ``` ts-node hello.ts ```type @@ -87,75 +87,26 @@ Check the `VIM_CHEATSHEET.md` for basic Vim commands! ## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -> **NEEDS_AUTHOR:** This lesson needs a complete answer key with code breakdown, execution process explanation, common errors table, and bonus knowledge section. Reference c-c++/stage-1/level-1/lesson.md for the gold standard format. - -### Key Concepts - -- Review the code structure specific to Typescript -- Understand the execution flow -- Learn common pitfalls and solutions - -### Next Steps - -Practice the code and experiment with variations! - ---- - -**Congratulations! Keep coding!** - - - -### Additional Content - -Understand the key concepts: - -- Review each function -- Understand the flow -- Learn the patterns used - - -### Code Review - -Key functions and their purpose: - -- Main function: Entry point -- Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```ts -console.log("Hello, World!"); - -```ts - -### Code Breakdown +``` +What should happen: +1. Print "Hello, [name]" -This solution demonstrates the key concepts from this lesson: +Write your pseudocode in plain English below: +(Your pseudocode here) +``` -1. **Structure**: The program follows standard typescript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions +### Explanation -### Testing Your Solution +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -Try these test cases to verify your code works correctly: +### Success Criteria -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does -### Tips for Understanding +--- -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs +**Great job! You've completed this lesson!** diff --git a/lessons/typescript/stage-3/level-2/lesson.md b/lessons/typescript/stage-3/level-2/lesson.md index e23251f..29cf20b 100644 --- a/lessons/typescript/stage-3/level-2/lesson.md +++ b/lessons/typescript/stage-3/level-2/lesson.md @@ -51,7 +51,7 @@ Data Structure Planning - Design an algorithm to solve this problem, then implem ### How to Run 1. **Run the code**: - ```bash + ``` ts-node hello.ts ```type @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```typescript +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -212,40 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```ts -console.log("Hello, World!"); - -```ts - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard typescript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/typescript/stage-3/level-3/lesson.md b/lessons/typescript/stage-3/level-3/lesson.md index a2b55bb..19e5dbe 100644 --- a/lessons/typescript/stage-3/level-3/lesson.md +++ b/lessons/typescript/stage-3/level-3/lesson.md @@ -51,7 +51,7 @@ Mathematical Problems - Design an algorithm to solve this problem, then implemen ### How to Run 1. **Run the code**: - ```bash + ``` ts-node hello.ts ```type @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```typescript +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -212,40 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```ts -console.log("Hello, World!"); - -```ts - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard typescript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/typescript/stage-3/level-4/lesson.md b/lessons/typescript/stage-3/level-4/lesson.md index b2ac519..87d9933 100644 --- a/lessons/typescript/stage-3/level-4/lesson.md +++ b/lessons/typescript/stage-3/level-4/lesson.md @@ -51,7 +51,7 @@ Text Processing Problems - Design an algorithm to solve this problem, then imple ### How to Run 1. **Run the code**: - ```bash + ``` ts-node hello.ts ```type @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```typescript +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -212,40 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```ts -console.log("Hello, World!"); - -```ts - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard typescript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/typescript/stage-3/level-5/lesson.md b/lessons/typescript/stage-3/level-5/lesson.md index 76ad141..429e37a 100644 --- a/lessons/typescript/stage-3/level-5/lesson.md +++ b/lessons/typescript/stage-3/level-5/lesson.md @@ -51,7 +51,7 @@ Logic Problems - Design an algorithm to solve this problem, then implement it. ### How to Run 1. **Run the code**: - ```bash + ``` ts-node hello.ts ```type @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```typescript +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -212,40 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```ts -console.log("Hello, World!"); - -```ts - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard typescript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/typescript/stage-3/level-6/lesson.md b/lessons/typescript/stage-3/level-6/lesson.md index 886853e..2ed951b 100644 --- a/lessons/typescript/stage-3/level-6/lesson.md +++ b/lessons/typescript/stage-3/level-6/lesson.md @@ -51,7 +51,7 @@ Search Algorithms - Design an algorithm to solve this problem, then implement it ### How to Run 1. **Run the code**: - ```bash + ``` ts-node hello.ts ```type @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```typescript +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -212,40 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```ts -console.log("Hello, World!"); - -```ts - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard typescript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/typescript/stage-3/level-7/lesson.md b/lessons/typescript/stage-3/level-7/lesson.md index 7639d59..9d6370a 100644 --- a/lessons/typescript/stage-3/level-7/lesson.md +++ b/lessons/typescript/stage-3/level-7/lesson.md @@ -51,7 +51,7 @@ Sorting Algorithms - Design an algorithm to solve this problem, then implement i ### How to Run 1. **Run the code**: - ```bash + ``` ts-node hello.ts ```type @@ -155,7 +155,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```typescript +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] @@ -212,40 +212,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```ts -console.log("Hello, World!"); - -```ts - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard typescript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/typescript/stage-4/level-1/lesson.md b/lessons/typescript/stage-4/level-1/lesson.md index c868b91..6d7500b 100644 --- a/lessons/typescript/stage-4/level-1/lesson.md +++ b/lessons/typescript/stage-4/level-1/lesson.md @@ -30,7 +30,7 @@ Requirements: ### How to Run 1. **Run the code**: - ```bash + ``` ts-node hello.ts ```type @@ -115,40 +115,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```ts -console.log("Hello, World!"); - -```ts - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard typescript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/typescript/stage-4/level-2/lesson.md b/lessons/typescript/stage-4/level-2/lesson.md index ffdb943..e94f626 100644 --- a/lessons/typescript/stage-4/level-2/lesson.md +++ b/lessons/typescript/stage-4/level-2/lesson.md @@ -51,7 +51,7 @@ Build a complete Text Analysis Tool application that: ### How to Run 1. **Run the code**: - ```bash + ``` ts-node hello.ts ```type @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```typescript +``` // Setup and initialization // Main program loop or flow // Helper functions @@ -207,40 +207,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```ts -console.log("Hello, World!"); - -```ts - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard typescript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/typescript/stage-4/level-3/lesson.md b/lessons/typescript/stage-4/level-3/lesson.md index 74abb88..31fb796 100644 --- a/lessons/typescript/stage-4/level-3/lesson.md +++ b/lessons/typescript/stage-4/level-3/lesson.md @@ -51,7 +51,7 @@ Build a complete Data Processing application that: ### How to Run 1. **Run the code**: - ```bash + ``` ts-node hello.ts ```type @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```typescript +``` // Setup and initialization // Main program loop or flow // Helper functions @@ -207,40 +207,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```ts -console.log("Hello, World!"); - -```ts - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard typescript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/typescript/stage-4/level-4/lesson.md b/lessons/typescript/stage-4/level-4/lesson.md index cdf2db9..a63b2f1 100644 --- a/lessons/typescript/stage-4/level-4/lesson.md +++ b/lessons/typescript/stage-4/level-4/lesson.md @@ -51,7 +51,7 @@ Build a complete File Operations application that: ### How to Run 1. **Run the code**: - ```bash + ``` ts-node hello.ts ```type @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```typescript +``` // Setup and initialization // Main program loop or flow // Helper functions @@ -207,40 +207,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```ts -console.log("Hello, World!"); - -```ts - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard typescript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/typescript/stage-4/level-5/lesson.md b/lessons/typescript/stage-4/level-5/lesson.md index a4e4228..6aecce2 100644 --- a/lessons/typescript/stage-4/level-5/lesson.md +++ b/lessons/typescript/stage-4/level-5/lesson.md @@ -51,7 +51,7 @@ Build a complete API Integration application that: ### How to Run 1. **Run the code**: - ```bash + ``` ts-node hello.ts ```type @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```typescript +``` // Setup and initialization // Main program loop or flow // Helper functions @@ -207,40 +207,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```ts -console.log("Hello, World!"); - -```ts - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard typescript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/typescript/stage-4/level-6/lesson.md b/lessons/typescript/stage-4/level-6/lesson.md index 165fdc2..46240a8 100644 --- a/lessons/typescript/stage-4/level-6/lesson.md +++ b/lessons/typescript/stage-4/level-6/lesson.md @@ -51,7 +51,7 @@ Build a complete Database Operations application that: ### How to Run 1. **Run the code**: - ```bash + ``` ts-node hello.ts ```type @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```typescript +``` // Setup and initialization // Main program loop or flow // Helper functions @@ -207,40 +207,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```ts -console.log("Hello, World!"); - -```ts - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard typescript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/typescript/stage-4/level-7/lesson.md b/lessons/typescript/stage-4/level-7/lesson.md index c3dde12..4c03ebc 100644 --- a/lessons/typescript/stage-4/level-7/lesson.md +++ b/lessons/typescript/stage-4/level-7/lesson.md @@ -51,7 +51,7 @@ Build a complete Complete Application application that: ### How to Run 1. **Run the code**: - ```bash + ``` ts-node hello.ts ```type @@ -158,7 +158,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```typescript +``` // Setup and initialization // Main program loop or flow // Helper functions @@ -207,40 +207,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```ts -console.log("Hello, World!"); - -```ts - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard typescript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/typescript/stage-5/level-1/lesson.md b/lessons/typescript/stage-5/level-1/lesson.md index 8cfdb54..daf6a0c 100644 --- a/lessons/typescript/stage-5/level-1/lesson.md +++ b/lessons/typescript/stage-5/level-1/lesson.md @@ -30,7 +30,7 @@ You're going to build a complete Typescript application. This is a real project ### How to Run 1. **Run the code**: - ```bash + ``` ts-node hello.ts ```type @@ -156,40 +156,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```ts -console.log("Hello, World!"); - -```ts - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard typescript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/typescript/stage-5/level-2/lesson.md b/lessons/typescript/stage-5/level-2/lesson.md index 728116f..978d158 100644 --- a/lessons/typescript/stage-5/level-2/lesson.md +++ b/lessons/typescript/stage-5/level-2/lesson.md @@ -58,7 +58,7 @@ Create a production-ready CLI Tool using Typescript with: ### How to Run 1. **Run the code**: - ```bash + ``` ts-node hello.ts ```type @@ -222,40 +222,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```ts -console.log("Hello, World!"); - -```ts - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard typescript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/typescript/stage-5/level-3/lesson.md b/lessons/typescript/stage-5/level-3/lesson.md index 122019d..03ccfb7 100644 --- a/lessons/typescript/stage-5/level-3/lesson.md +++ b/lessons/typescript/stage-5/level-3/lesson.md @@ -58,7 +58,7 @@ Create a production-ready REST API using Typescript with: ### How to Run 1. **Run the code**: - ```bash + ``` ts-node hello.ts ```type @@ -222,40 +222,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```ts -console.log("Hello, World!"); - -```ts - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard typescript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/typescript/stage-5/level-4/lesson.md b/lessons/typescript/stage-5/level-4/lesson.md index 7918c68..2a16c28 100644 --- a/lessons/typescript/stage-5/level-4/lesson.md +++ b/lessons/typescript/stage-5/level-4/lesson.md @@ -58,7 +58,7 @@ Create a production-ready Data Visualization using Typescript with: ### How to Run 1. **Run the code**: - ```bash + ``` ts-node hello.ts ```type @@ -222,40 +222,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```ts -console.log("Hello, World!"); - -```ts - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard typescript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/typescript/stage-5/level-5/lesson.md b/lessons/typescript/stage-5/level-5/lesson.md index 8a23f9b..ec660bb 100644 --- a/lessons/typescript/stage-5/level-5/lesson.md +++ b/lessons/typescript/stage-5/level-5/lesson.md @@ -58,7 +58,7 @@ Create a production-ready Automated Testing using Typescript with: ### How to Run 1. **Run the code**: - ```bash + ``` ts-node hello.ts ```type @@ -222,40 +222,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```ts -console.log("Hello, World!"); - -```ts - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard typescript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/typescript/stage-5/level-6/lesson.md b/lessons/typescript/stage-5/level-6/lesson.md index 7fd1758..3bddbcb 100644 --- a/lessons/typescript/stage-5/level-6/lesson.md +++ b/lessons/typescript/stage-5/level-6/lesson.md @@ -58,7 +58,7 @@ Create a production-ready Performance Optimization using Typescript with: ### How to Run 1. **Run the code**: - ```bash + ``` ts-node hello.ts ```type @@ -222,40 +222,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```ts -console.log("Hello, World!"); - -```ts - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard typescript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/typescript/stage-5/level-7/lesson.md b/lessons/typescript/stage-5/level-7/lesson.md index 6f11d74..80d1f33 100644 --- a/lessons/typescript/stage-5/level-7/lesson.md +++ b/lessons/typescript/stage-5/level-7/lesson.md @@ -58,7 +58,7 @@ Create a production-ready Final Capstone Project using Typescript with: ### How to Run 1. **Run the code**: - ```bash + ``` ts-node hello.ts ```type @@ -222,40 +222,3 @@ Key functions and their purpose: - Main function: Entry point - Helper functions: Support logic - - -
- -## Answer Key - -### Complete Solution - -```ts -console.log("Hello, World!"); - -```ts - -### Code Breakdown - -This solution demonstrates the key concepts from this lesson: - -1. **Structure**: The program follows standard typescript conventions with proper imports and main function -2. **Variables**: Data types are correctly declared and initialized -3. **Logic**: The program implements the required functionality -4. **Output**: Results are displayed clearly to the user -5. **Best Practices**: Code is readable and follows naming conventions - -### Testing Your Solution - -Try these test cases to verify your code works correctly: - -1. **Basic Test**: Run the program with standard inputs -2. **Edge Cases**: Test with boundary values (0, -1, very large numbers) -3. **Error Handling**: Verify the program handles invalid inputs gracefully - -### Tips for Understanding - -- Review each section carefully -- Try modifying values to see how output changes -- Add your own printf/print statements to trace execution -- Experiment with different inputs diff --git a/lessons/zig/stage-1/level-1/lesson.md b/lessons/zig/stage-1/level-1/lesson.md index fad9c6e..e61a5f0 100644 --- a/lessons/zig/stage-1/level-1/lesson.md +++ b/lessons/zig/stage-1/level-1/lesson.md @@ -23,7 +23,7 @@ Welcome to your first Zig program! Today, you'll create and run your very first **Copy the following code EXACTLY as shown below into `main.zig`** -```zig +``` const std = @import("std"); pub fn main() !void { @@ -37,12 +37,12 @@ pub fn main() !void { ### How to Run **Method 1 (Vim - Recommended):** -```zig +``` r ``` **Method 2 (Terminal):** -```bash +``` zig build-exe main.zig ./main ``` @@ -98,45 +98,29 @@ You just created a real Zig program! Here's what makes it work: --- -## ANSWER KEY (No peeking until you've tried!) - -### Code Breakdown +## ANSWER KEY (No cheating until you've tried!) -The code you copied demonstrates fundamental Zig concepts: +### Solution -**Key Components:** -- Syntax rules specific to Zig -- How data is stored and manipulated -- Input/output operations -- Program flow and structure - -### Common Errors & Solutions +``` +const std = @import("std"); -| Error | Cause | Solution | -|-------|-------|----------| -| Syntax error | Typo in code | Double-check spelling and punctuation | -| Runtime error | Code runs but crashes | Check your logic and data types | -| Unexpected output | Logic error | Review your algorithm step-by-step | -| Compilation error | Code won't compile | Fix syntax before running | +pub fn main() !void { + const stdout = std.io.getStdOut().writer(); + try stdout.print("Hello, World!\n", .{}); +} +``` -### Bonus Knowledge +### Explanation -- Zig has a rich ecosystem of libraries and tools -- Understanding these basics prepares you for advanced topics -- Practice is key - try writing similar programs from scratch -- Every expert programmer started exactly where you are now! +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -### Real-World Applications +### Success Criteria -This concept is used in: -1. Professional software development -2. Web applications and mobile apps -3. Data analysis and scientific computing -4. Automation and scripting -5. Game development +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -**Excellent work! You've mastered a fundamental concept!** - -*Ready for the next challenge? Keep going!* +**Great job! You've completed this lesson!** diff --git a/lessons/zig/stage-1/level-2/lesson.md b/lessons/zig/stage-1/level-2/lesson.md index 4819a00..8cb7c25 100644 --- a/lessons/zig/stage-1/level-2/lesson.md +++ b/lessons/zig/stage-1/level-2/lesson.md @@ -23,22 +23,22 @@ Learn how to store and work with different types of data in Zig. **Copy the following code EXACTLY as shown below into `main.zig`** -```zig +``` const std = @import("std"); pub fn main() !void { const stdout = std.io.getStdOut().writer(); - + // Integer variables const age: i32 = 25; const score: i32 = 100; - + // Floating point const price: f64 = 29.99; - + // String const name = "Alex"; - + // Display try stdout.print("Name: {s}\n", .{name}); try stdout.print("Age: {}\n", .{age}); @@ -51,12 +51,12 @@ pub fn main() !void { ### How to Run **Method 1 (Vim - Recommended):** -```zig +``` r ``` **Method 2 (Terminal):** -```bash +``` zig build-exe main.zig ./main ``` @@ -114,45 +114,43 @@ You just created a real Zig program! Here's what makes it work: --- -## ANSWER KEY (No peeking until you've tried!) +## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -The code you copied demonstrates fundamental Zig concepts: +``` +const std = @import("std"); -**Key Components:** -- Syntax rules specific to Zig -- How data is stored and manipulated -- Input/output operations -- Program flow and structure +pub fn main() !void { + const stdout = std.io.getStdOut().writer(); -### Common Errors & Solutions + // Integer variables + const age: i32 = 25; + const score: i32 = 100; -| Error | Cause | Solution | -|-------|-------|----------| -| Syntax error | Typo in code | Double-check spelling and punctuation | -| Runtime error | Code runs but crashes | Check your logic and data types | -| Unexpected output | Logic error | Review your algorithm step-by-step | -| Compilation error | Code won't compile | Fix syntax before running | + // Floating point + const price: f64 = 29.99; -### Bonus Knowledge + // String + const name = "Alex"; -- Zig has a rich ecosystem of libraries and tools -- Understanding these basics prepares you for advanced topics -- Practice is key - try writing similar programs from scratch -- Every expert programmer started exactly where you are now! + // Display + try stdout.print("Name: {s}\n", .{name}); + try stdout.print("Age: {}\n", .{age}); + try stdout.print("Price: ${d:.2}\n", .{price}); +} +``` -### Real-World Applications +### Explanation -This concept is used in: -1. Professional software development -2. Web applications and mobile apps -3. Data analysis and scientific computing -4. Automation and scripting -5. Game development +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. ---- +### Success Criteria + +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does -**Excellent work! You've mastered a fundamental concept!** +--- -*Ready for the next challenge? Keep going!* +**Great job! You've completed this lesson!** diff --git a/lessons/zig/stage-1/level-3/lesson.md b/lessons/zig/stage-1/level-3/lesson.md index f64492c..bca0281 100644 --- a/lessons/zig/stage-1/level-3/lesson.md +++ b/lessons/zig/stage-1/level-3/lesson.md @@ -23,21 +23,21 @@ Master arithmetic operations and use Zig as your powerful calculator. **Copy the following code EXACTLY as shown below into `main.zig`** -```zig +``` const std = @import("std"); pub fn main() !void { const stdout = std.io.getStdOut().writer(); - + const a: i32 = 10; const b: i32 = 3; - + try stdout.print("Addition: {}\n", .{a + b}); try stdout.print("Subtraction: {}\n", .{a - b}); try stdout.print("Multiplication: {}\n", .{a * b}); try stdout.print("Division: {}\n", .{@divTrunc(a, b)}); try stdout.print("Modulus: {}\n", .{@mod(a, b)}); - + const x: f64 = 10.0; const y: f64 = 3.0; try stdout.print("Float division: {d:.2}\n", .{x / y}); @@ -49,12 +49,12 @@ pub fn main() !void { ### How to Run **Method 1 (Vim - Recommended):** -```zig +``` r ``` **Method 2 (Terminal):** -```bash +``` zig build-exe main.zig ./main ``` @@ -113,45 +113,41 @@ You just created a real Zig program! Here's what makes it work: --- -## ANSWER KEY (No peeking until you've tried!) +## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -The code you copied demonstrates fundamental Zig concepts: +``` +const std = @import("std"); + +pub fn main() !void { + const stdout = std.io.getStdOut().writer(); -**Key Components:** -- Syntax rules specific to Zig -- How data is stored and manipulated -- Input/output operations -- Program flow and structure + const a: i32 = 10; + const b: i32 = 3; -### Common Errors & Solutions + try stdout.print("Addition: {}\n", .{a + b}); + try stdout.print("Subtraction: {}\n", .{a - b}); + try stdout.print("Multiplication: {}\n", .{a * b}); + try stdout.print("Division: {}\n", .{@divTrunc(a, b)}); + try stdout.print("Modulus: {}\n", .{@mod(a, b)}); -| Error | Cause | Solution | -|-------|-------|----------| -| Syntax error | Typo in code | Double-check spelling and punctuation | -| Runtime error | Code runs but crashes | Check your logic and data types | -| Unexpected output | Logic error | Review your algorithm step-by-step | -| Compilation error | Code won't compile | Fix syntax before running | + const x: f64 = 10.0; + const y: f64 = 3.0; + try stdout.print("Float division: {d:.2}\n", .{x / y}); +} +``` -### Bonus Knowledge +### Explanation -- Zig has a rich ecosystem of libraries and tools -- Understanding these basics prepares you for advanced topics -- Practice is key - try writing similar programs from scratch -- Every expert programmer started exactly where you are now! +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -### Real-World Applications +### Success Criteria -This concept is used in: -1. Professional software development -2. Web applications and mobile apps -3. Data analysis and scientific computing -4. Automation and scripting -5. Game development +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -**Excellent work! You've mastered a fundamental concept!** - -*Ready for the next challenge? Keep going!* +**Great job! You've completed this lesson!** diff --git a/lessons/zig/stage-1/level-4/lesson.md b/lessons/zig/stage-1/level-4/lesson.md index 6566fac..e517d17 100644 --- a/lessons/zig/stage-1/level-4/lesson.md +++ b/lessons/zig/stage-1/level-4/lesson.md @@ -23,18 +23,18 @@ Make your programs interactive by reading input from users. **Copy the following code EXACTLY as shown below into `main.zig`** -```zig +``` const std = @import("std"); pub fn main() !void { const stdout = std.io.getStdOut().writer(); const stdin = std.io.getStdIn().reader(); - + var name_buf: [100]u8 = undefined; - + try stdout.print("Enter your name: ", .{}); const name = try stdin.readUntilDelimiter(&name_buf, '\n'); - + try stdout.print("Hello, {s}!\n", .{name}); } ``` @@ -44,12 +44,12 @@ pub fn main() !void { ### How to Run **Method 1 (Vim - Recommended):** -```zig +``` r ``` **Method 2 (Terminal):** -```bash +``` zig build-exe main.zig ./main ``` @@ -105,45 +105,36 @@ You just created a real Zig program! Here's what makes it work: --- -## ANSWER KEY (No peeking until you've tried!) +## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -The code you copied demonstrates fundamental Zig concepts: +``` +const std = @import("std"); -**Key Components:** -- Syntax rules specific to Zig -- How data is stored and manipulated -- Input/output operations -- Program flow and structure +pub fn main() !void { + const stdout = std.io.getStdOut().writer(); + const stdin = std.io.getStdIn().reader(); -### Common Errors & Solutions + var name_buf: [100]u8 = undefined; -| Error | Cause | Solution | -|-------|-------|----------| -| Syntax error | Typo in code | Double-check spelling and punctuation | -| Runtime error | Code runs but crashes | Check your logic and data types | -| Unexpected output | Logic error | Review your algorithm step-by-step | -| Compilation error | Code won't compile | Fix syntax before running | + try stdout.print("Enter your name: ", .{}); + const name = try stdin.readUntilDelimiter(&name_buf, '\n'); -### Bonus Knowledge + try stdout.print("Hello, {s}!\n", .{name}); +} +``` -- Zig has a rich ecosystem of libraries and tools -- Understanding these basics prepares you for advanced topics -- Practice is key - try writing similar programs from scratch -- Every expert programmer started exactly where you are now! +### Explanation -### Real-World Applications +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -This concept is used in: -1. Professional software development -2. Web applications and mobile apps -3. Data analysis and scientific computing -4. Automation and scripting -5. Game development +### Success Criteria ---- +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does -**Excellent work! You've mastered a fundamental concept!** +--- -*Ready for the next challenge? Keep going!* +**Great job! You've completed this lesson!** diff --git a/lessons/zig/stage-1/level-5/lesson.md b/lessons/zig/stage-1/level-5/lesson.md index 7b57701..e329f41 100644 --- a/lessons/zig/stage-1/level-5/lesson.md +++ b/lessons/zig/stage-1/level-5/lesson.md @@ -23,19 +23,19 @@ Add decision-making to your programs with if/else statements. **Copy the following code EXACTLY as shown below into `main.zig`** -```zig +``` const std = @import("std"); pub fn main() !void { const stdout = std.io.getStdOut().writer(); const stdin = std.io.getStdIn().reader(); - + try stdout.print("Enter your score (0-100): ", .{}); - + var buf: [10]u8 = undefined; const input = try stdin.readUntilDelimiter(&buf, '\n'); const score = try std.fmt.parseInt(i32, input, 10); - + if (score >= 90) { try stdout.print("Grade: A - Excellent!\n", .{}); } else if (score >= 80) { @@ -55,12 +55,12 @@ pub fn main() !void { ### How to Run **Method 1 (Vim - Recommended):** -```zig +``` r ``` **Method 2 (Terminal):** -```bash +``` zig build-exe main.zig ./main ``` @@ -116,45 +116,47 @@ You just created a real Zig program! Here's what makes it work: --- -## ANSWER KEY (No peeking until you've tried!) +## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -The code you copied demonstrates fundamental Zig concepts: +``` +const std = @import("std"); -**Key Components:** -- Syntax rules specific to Zig -- How data is stored and manipulated -- Input/output operations -- Program flow and structure +pub fn main() !void { + const stdout = std.io.getStdOut().writer(); + const stdin = std.io.getStdIn().reader(); -### Common Errors & Solutions + try stdout.print("Enter your score (0-100): ", .{}); + + var buf: [10]u8 = undefined; + const input = try stdin.readUntilDelimiter(&buf, '\n'); + const score = try std.fmt.parseInt(i32, input, 10); -| Error | Cause | Solution | -|-------|-------|----------| -| Syntax error | Typo in code | Double-check spelling and punctuation | -| Runtime error | Code runs but crashes | Check your logic and data types | -| Unexpected output | Logic error | Review your algorithm step-by-step | -| Compilation error | Code won't compile | Fix syntax before running | + if (score >= 90) { + try stdout.print("Grade: A - Excellent!\n", .{}); + } else if (score >= 80) { + try stdout.print("Grade: B - Good job!\n", .{}); + } else if (score >= 70) { + try stdout.print("Grade: C - Passing\n", .{}); + } else if (score >= 60) { + try stdout.print("Grade: D - Needs improvement\n", .{}); + } else { + try stdout.print("Grade: F - Study harder!\n", .{}); + } +} +``` -### Bonus Knowledge +### Explanation -- Zig has a rich ecosystem of libraries and tools -- Understanding these basics prepares you for advanced topics -- Practice is key - try writing similar programs from scratch -- Every expert programmer started exactly where you are now! +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -### Real-World Applications +### Success Criteria -This concept is used in: -1. Professional software development -2. Web applications and mobile apps -3. Data analysis and scientific computing -4. Automation and scripting -5. Game development +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -**Excellent work! You've mastered a fundamental concept!** - -*Ready for the next challenge? Keep going!* +**Great job! You've completed this lesson!** diff --git a/lessons/zig/stage-1/level-6/lesson.md b/lessons/zig/stage-1/level-6/lesson.md index eaeeb30..45c87b3 100644 --- a/lessons/zig/stage-1/level-6/lesson.md +++ b/lessons/zig/stage-1/level-6/lesson.md @@ -23,12 +23,12 @@ Learn to repeat actions efficiently using loops. **Copy the following code EXACTLY as shown below into `main.zig`** -```zig +``` const std = @import("std"); pub fn main() !void { const stdout = std.io.getStdOut().writer(); - + // For loop try stdout.print("Counting 1 to 10:\n", .{}); var i: i32 = 1; @@ -36,7 +36,7 @@ pub fn main() !void { try stdout.print("{} ", .{i}); } try stdout.print("\n", .{}); - + // While loop try stdout.print("\nCountdown:\n", .{}); var count: i32 = 5; @@ -45,7 +45,7 @@ pub fn main() !void { count -= 1; } try stdout.print("Blastoff!\n", .{}); - + // Multiplication table const num: i32 = 7; try stdout.print("\n{} times table:\n", .{num}); @@ -61,12 +61,12 @@ pub fn main() !void { ### How to Run **Method 1 (Vim - Recommended):** -```zig +``` r ``` **Method 2 (Terminal):** -```bash +``` zig build-exe main.zig ./main ``` @@ -122,45 +122,53 @@ You just created a real Zig program! Here's what makes it work: --- -## ANSWER KEY (No peeking until you've tried!) +## ANSWER KEY (No cheating until you've tried!) + +### Solution -### Code Breakdown +``` +const std = @import("std"); -The code you copied demonstrates fundamental Zig concepts: +pub fn main() !void { + const stdout = std.io.getStdOut().writer(); -**Key Components:** -- Syntax rules specific to Zig -- How data is stored and manipulated -- Input/output operations -- Program flow and structure + // For loop + try stdout.print("Counting 1 to 10:\n", .{}); + var i: i32 = 1; + while (i <= 10) : (i += 1) { + try stdout.print("{} ", .{i}); + } + try stdout.print("\n", .{}); -### Common Errors & Solutions + // While loop + try stdout.print("\nCountdown:\n", .{}); + var count: i32 = 5; + while (count > 0) { + try stdout.print("{}\n", .{count}); + count -= 1; + } + try stdout.print("Blastoff!\n", .{}); -| Error | Cause | Solution | -|-------|-------|----------| -| Syntax error | Typo in code | Double-check spelling and punctuation | -| Runtime error | Code runs but crashes | Check your logic and data types | -| Unexpected output | Logic error | Review your algorithm step-by-step | -| Compilation error | Code won't compile | Fix syntax before running | + // Multiplication table + const num: i32 = 7; + try stdout.print("\n{} times table:\n", .{num}); + i = 1; + while (i <= 10) : (i += 1) { + try stdout.print("{} × {} = {}\n", .{num, i, num * i}); + } +} +``` -### Bonus Knowledge +### Explanation -- Zig has a rich ecosystem of libraries and tools -- Understanding these basics prepares you for advanced topics -- Practice is key - try writing similar programs from scratch -- Every expert programmer started exactly where you are now! +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. -### Real-World Applications +### Success Criteria -This concept is used in: -1. Professional software development -2. Web applications and mobile apps -3. Data analysis and scientific computing -4. Automation and scripting -5. Game development +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does --- -**Excellent work! You've mastered a fundamental concept!** - -*Ready for the next challenge? Keep going!* +**Great job! You've completed this lesson!** diff --git a/lessons/zig/stage-1/level-7/lesson.md b/lessons/zig/stage-1/level-7/lesson.md index 0c8f563..5ebfa6f 100644 --- a/lessons/zig/stage-1/level-7/lesson.md +++ b/lessons/zig/stage-1/level-7/lesson.md @@ -23,7 +23,7 @@ Organize your code into reusable functions/methods. **Copy the following code EXACTLY as shown below into `main.zig`** -```zig +``` const std = @import("std"); fn greet(name: []const u8) !void { @@ -46,13 +46,13 @@ fn factorial(n: i32) i64 { pub fn main() !void { const stdout = std.io.getStdOut().writer(); - + try greet("Alice"); try greet("Bob"); - + const sum = add(5, 3); try stdout.print("5 + 3 = {}\n", .{sum}); - + try stdout.print("5! = {}\n", .{factorial(5)}); } ``` @@ -62,12 +62,12 @@ pub fn main() !void { ### How to Run **Method 1 (Vim - Recommended):** -```zig +``` r ``` **Method 2 (Terminal):** -```bash +``` zig build-exe main.zig ./main ``` @@ -123,45 +123,54 @@ You just created a real Zig program! Here's what makes it work: --- -## ANSWER KEY (No peeking until you've tried!) +## ANSWER KEY (No cheating until you've tried!) -### Code Breakdown +### Solution -The code you copied demonstrates fundamental Zig concepts: +``` +const std = @import("std"); -**Key Components:** -- Syntax rules specific to Zig -- How data is stored and manipulated -- Input/output operations -- Program flow and structure +fn greet(name: []const u8) !void { + const stdout = std.io.getStdOut().writer(); + try stdout.print("Hello, {s}!\n", .{name}); +} -### Common Errors & Solutions +fn add(a: i32, b: i32) i32 { + return a + b; +} -| Error | Cause | Solution | -|-------|-------|----------| -| Syntax error | Typo in code | Double-check spelling and punctuation | -| Runtime error | Code runs but crashes | Check your logic and data types | -| Unexpected output | Logic error | Review your algorithm step-by-step | -| Compilation error | Code won't compile | Fix syntax before running | +fn factorial(n: i32) i64 { + var result: i64 = 1; + var i: i32 = 1; + while (i <= n) : (i += 1) { + result *= i; + } + return result; +} + +pub fn main() !void { + const stdout = std.io.getStdOut().writer(); + + try greet("Alice"); + try greet("Bob"); -### Bonus Knowledge + const sum = add(5, 3); + try stdout.print("5 + 3 = {}\n", .{sum}); -- Zig has a rich ecosystem of libraries and tools -- Understanding these basics prepares you for advanced topics -- Practice is key - try writing similar programs from scratch -- Every expert programmer started exactly where you are now! + try stdout.print("5! = {}\n", .{factorial(5)}); +} +``` -### Real-World Applications +### Explanation -This concept is used in: -1. Professional software development -2. Web applications and mobile apps -3. Data analysis and scientific computing -4. Automation and scripting -5. Game development +This solution demonstrates the key concepts from this lesson. Copy this code exactly as shown, and make sure you understand each part before moving on. ---- +### Success Criteria -**Excellent work! You've mastered a fundamental concept!** +- [ ] Code runs without errors +- [ ] Output matches expected result +- [ ] You understand what each line does + +--- -*Ready for the next challenge? Keep going!* +**Great job! You've completed this lesson!** diff --git a/lessons/zig/stage-2/level-1/lesson.md b/lessons/zig/stage-2/level-1/lesson.md index 325a32d..6f2afb5 100644 --- a/lessons/zig/stage-2/level-1/lesson.md +++ b/lessons/zig/stage-2/level-1/lesson.md @@ -30,18 +30,18 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Zig:** -```zig +``` ALGORITHM: Greeting Generator BEGIN INPUT: user's name (string) - + PROCESSING: 1. Create a personalized greeting message - 2. Append the current date to the message + 2. Append the current date to the message 3. Calculate the length of the greeting - - OUTPUT: + + OUTPUT: - Display the personalized greeting - Show the length of the message - Print a border of asterisks matching the greeting length @@ -61,12 +61,12 @@ END ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` zig build-exe hello.zig ``` 2. **Run your program**: - ```bash + ``` ./hello hello ``` @@ -172,26 +172,26 @@ The key is understanding what each pseudocode statement represents in Zig: 5. **Calculation**: `calculate length` → `string.len` property **Zig Implementation:** -```zig +``` const std = @import("std"); pub fn main() !void { const stdout = std.io.getStdOut().writer(); - + // Sample name (in a complete program, you'd get user input) const name = "Alex"; - + // Create personalized greeting var greeting = try std.fmt.allocPrint(std.heap.page_allocator, "Hello, {s}! Welcome!", .{name}); defer std.heap.page_allocator.free(greeting); - + // Calculate length const greeting_length = greeting.len; - + // Print greeting try stdout.print("{s}\n", .{greeting}); try stdout.print("Message length: {d} characters\n", .{greeting_length}); - + // Print border of asterisks var i: usize = 0; while (i < greeting_length) : (i += 1) { diff --git a/lessons/zig/stage-2/level-2/lesson.md b/lessons/zig/stage-2/level-2/lesson.md index 5ca10f5..929285e 100644 --- a/lessons/zig/stage-2/level-2/lesson.md +++ b/lessons/zig/stage-2/level-2/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Zig:** -```zig +``` ALGORITHM: Variables in Algorithms BEGIN @@ -54,12 +54,12 @@ END ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` zig build-exe hello.zig ``` 2. **Run your program**: - ```bash + ``` ./hello hello ``` @@ -165,7 +165,7 @@ The key is understanding what each pseudocode statement represents in Zig: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```zig +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/zig/stage-2/level-3/lesson.md b/lessons/zig/stage-2/level-3/lesson.md index c19f5df..5bdded6 100644 --- a/lessons/zig/stage-2/level-3/lesson.md +++ b/lessons/zig/stage-2/level-3/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Zig:** -```zig +``` ALGORITHM: Mathematical Algorithms BEGIN @@ -54,12 +54,12 @@ END ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` zig build-exe hello.zig ``` 2. **Run your program**: - ```bash + ``` ./hello hello ``` @@ -165,7 +165,7 @@ The key is understanding what each pseudocode statement represents in Zig: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```zig +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/zig/stage-2/level-4/lesson.md b/lessons/zig/stage-2/level-4/lesson.md index 1407041..6befe93 100644 --- a/lessons/zig/stage-2/level-4/lesson.md +++ b/lessons/zig/stage-2/level-4/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Zig:** -```zig +``` ALGORITHM: Input/Output Algorithms BEGIN @@ -54,12 +54,12 @@ END ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` zig build-exe hello.zig ``` 2. **Run your program**: - ```bash + ``` ./hello hello ``` @@ -165,7 +165,7 @@ The key is understanding what each pseudocode statement represents in Zig: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```zig +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/zig/stage-2/level-5/lesson.md b/lessons/zig/stage-2/level-5/lesson.md index 7a6e911..e4343d3 100644 --- a/lessons/zig/stage-2/level-5/lesson.md +++ b/lessons/zig/stage-2/level-5/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Zig:** -```zig +``` ALGORITHM: Decision Algorithms BEGIN @@ -54,12 +54,12 @@ END ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` zig build-exe hello.zig ``` 2. **Run your program**: - ```bash + ``` ./hello hello ``` @@ -165,7 +165,7 @@ The key is understanding what each pseudocode statement represents in Zig: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```zig +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/zig/stage-2/level-6/lesson.md b/lessons/zig/stage-2/level-6/lesson.md index bc7e57f..1b234a5 100644 --- a/lessons/zig/stage-2/level-6/lesson.md +++ b/lessons/zig/stage-2/level-6/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Zig:** -```zig +``` ALGORITHM: Loop Algorithms BEGIN @@ -54,12 +54,12 @@ END ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` zig build-exe hello.zig ``` 2. **Run your program**: - ```bash + ``` ./hello hello ``` @@ -165,7 +165,7 @@ The key is understanding what each pseudocode statement represents in Zig: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```zig +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/zig/stage-2/level-7/lesson.md b/lessons/zig/stage-2/level-7/lesson.md index 3afa53a..aae4e48 100644 --- a/lessons/zig/stage-2/level-7/lesson.md +++ b/lessons/zig/stage-2/level-7/lesson.md @@ -30,7 +30,7 @@ You've mastered the basics! Now you'll learn to translate written algorithms (ps **Study the pseudocode algorithm below, then implement it in Zig:** -```zig +``` ALGORITHM: Function Design BEGIN @@ -54,12 +54,12 @@ END ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` zig build-exe hello.zig ``` 2. **Run your program**: - ```bash + ``` ./hello hello ``` @@ -165,7 +165,7 @@ The key is understanding what each pseudocode statement represents in Zig: 5. **Conditions**: `IF...THEN...ELSE` → if/else statements **Example Translation:** -```zig +``` PSEUDOCODE: READ number IF number > 0 THEN diff --git a/lessons/zig/stage-3/level-1/lesson.md b/lessons/zig/stage-3/level-1/lesson.md index 385fe73..08c8811 100644 --- a/lessons/zig/stage-3/level-1/lesson.md +++ b/lessons/zig/stage-3/level-1/lesson.md @@ -34,7 +34,7 @@ Time to think like a programmer! You'll analyze real problems and design solutio Create a temperature conversion tool that allows users to convert between Celsius and Fahrenheit. The program should provide a simple menu interface where users can choose the conversion direction and input the temperature value. **Your Process:** -1. **Understand**: +1. **Understand**: - Input: Temperature value and conversion choice (C→F or F→C) - Output: Converted temperature value - Formulas: C to F: (C * 9/5) + 32, F to C: (F - 32) * 5/9 @@ -54,12 +54,12 @@ Create a temperature conversion tool that allows users to convert between Celsiu ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` zig build-exe hello.zig ``` 2. **Run your program**: - ```bash + ``` ./hello hello ``` @@ -163,7 +163,7 @@ Hello, World! 4. **Edge Cases**: Invalid input values, non-numeric input **Pseudocode Design:** -```zig +``` ALGORITHM: Temperature Converter INPUT: temperature value (number), conversion choice (C or F) OUTPUT: converted temperature value @@ -174,34 +174,34 @@ BEGIN 3. Get temperature value from user 4. IF choice is 1 (C to F) THEN apply formula: (C * 9/5) + 32 - 5. ELSE IF choice is 2 (F to C) + 5. ELSE IF choice is 2 (F to C) THEN apply formula: (F - 32) * 5/9 6. Display result END ``` **Zig Implementation:** -```zig +``` const std = @import("std"); pub fn main() !void { const stdout = std.io.getStdOut().writer(); const stdin = std.io.getStdIn().reader(); - + try stdout.print("Temperature Converter\\n", .{}); try stdout.print("1. Celsius to Fahrenheit\\n", .{}); try stdout.print("2. Fahrenheit to Celsius\\n", .{}); try stdout.print("Choose (1 or 2): ", .{}); - + var buf: [10]u8 = undefined; _ = try stdin.readUntilDelimiterOrEof(&buf, '\n'); - + const choice = std.fmt.parseInt(u8, std.mem.trimRight(u8, &buf, "\n\r"), 10) catch 0; - + try stdout.print("Enter temperature: ", .{}); _ = try stdin.readUntilDelimiterOrEof(&buf, '\n'); const temp = std.fmt.parseFloat(f64, std.mem.trimRight(u8, &buf, "\n\r")) catch 0.0; - + var result: f64 = 0.0; if (choice == 1) { result = (temp * 9.0 / 5.0) + 32.0; diff --git a/lessons/zig/stage-3/level-2/lesson.md b/lessons/zig/stage-3/level-2/lesson.md index 7bae186..fa3a8e0 100644 --- a/lessons/zig/stage-3/level-2/lesson.md +++ b/lessons/zig/stage-3/level-2/lesson.md @@ -51,12 +51,12 @@ Data Structure Planning - Design an algorithm to solve this problem, then implem ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` zig build-exe hello.zig ``` 2. **Run your program**: - ```bash + ``` ./hello hello ``` @@ -160,7 +160,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```zig +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/zig/stage-3/level-3/lesson.md b/lessons/zig/stage-3/level-3/lesson.md index 8de4b28..50c214d 100644 --- a/lessons/zig/stage-3/level-3/lesson.md +++ b/lessons/zig/stage-3/level-3/lesson.md @@ -51,12 +51,12 @@ Mathematical Problems - Design an algorithm to solve this problem, then implemen ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` zig build-exe hello.zig ``` 2. **Run your program**: - ```bash + ``` ./hello hello ``` @@ -160,7 +160,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```zig +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/zig/stage-3/level-4/lesson.md b/lessons/zig/stage-3/level-4/lesson.md index a0ee88b..5af8dc4 100644 --- a/lessons/zig/stage-3/level-4/lesson.md +++ b/lessons/zig/stage-3/level-4/lesson.md @@ -51,12 +51,12 @@ Text Processing Problems - Design an algorithm to solve this problem, then imple ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` zig build-exe hello.zig ``` 2. **Run your program**: - ```bash + ``` ./hello hello ``` @@ -160,7 +160,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```zig +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/zig/stage-3/level-5/lesson.md b/lessons/zig/stage-3/level-5/lesson.md index e3b80f9..b54d460 100644 --- a/lessons/zig/stage-3/level-5/lesson.md +++ b/lessons/zig/stage-3/level-5/lesson.md @@ -51,12 +51,12 @@ Logic Problems - Design an algorithm to solve this problem, then implement it. ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` zig build-exe hello.zig ``` 2. **Run your program**: - ```bash + ``` ./hello hello ``` @@ -160,7 +160,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```zig +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/zig/stage-3/level-6/lesson.md b/lessons/zig/stage-3/level-6/lesson.md index 7543473..4d928d7 100644 --- a/lessons/zig/stage-3/level-6/lesson.md +++ b/lessons/zig/stage-3/level-6/lesson.md @@ -51,12 +51,12 @@ Search Algorithms - Design an algorithm to solve this problem, then implement it ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` zig build-exe hello.zig ``` 2. **Run your program**: - ```bash + ``` ./hello hello ``` @@ -160,7 +160,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```zig +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/zig/stage-3/level-7/lesson.md b/lessons/zig/stage-3/level-7/lesson.md index 53892a6..7dc9530 100644 --- a/lessons/zig/stage-3/level-7/lesson.md +++ b/lessons/zig/stage-3/level-7/lesson.md @@ -51,12 +51,12 @@ Sorting Algorithms - Design an algorithm to solve this problem, then implement i ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` zig build-exe hello.zig ``` 2. **Run your program**: - ```bash + ``` ./hello hello ``` @@ -160,7 +160,7 @@ Hello, World! 4. **Edge Cases**: What could go wrong? **Pseudocode Template:** -```zig +``` ALGORITHM: [Name] INPUT: [What we need] OUTPUT: [What we produce] diff --git a/lessons/zig/stage-4/level-1/lesson.md b/lessons/zig/stage-4/level-1/lesson.md index a94c963..dffd560 100644 --- a/lessons/zig/stage-4/level-1/lesson.md +++ b/lessons/zig/stage-4/level-1/lesson.md @@ -59,12 +59,12 @@ Build a complete Calculator Application that supports basic arithmetic operation ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` zig build-exe hello.zig ``` 2. **Run your program**: - ```bash + ``` ./hello hello ``` @@ -171,7 +171,7 @@ A complete calculator application has these components: 5. **Error Handling**: Manage division by zero and invalid input **Zig Implementation:** -```zig +``` const std = @import("std"); // Function to perform addition @@ -200,10 +200,10 @@ fn divide(x: f64, y: f64) !f64 { pub fn main() !void { const stdout = std.io.getStdOut().writer(); const stdin = std.io.getStdIn().reader(); - + var continue_calc: bool = true; var input_buf: [100]u8 = undefined; - + while (continue_calc) { // Display menu try stdout.print("\\n--- Calculator ---\\n", .{}); @@ -213,31 +213,31 @@ pub fn main() !void { try stdout.print("4. Divide (/)\\n", .{}); try stdout.print("5. Exit\\n", .{}); try stdout.print("Choose operation (1-5): ", .{}); - + // Get user choice _ = try stdin.readUntilDelimiterOrEof(&input_buf, '\n'); const choice = std.fmt.parseInt(u8, std.mem.trimRight(u8, &input_buf, "\n\r"), 10) catch 0; - + if (choice == 5) { continue_calc = false; try stdout.print("Goodbye!\\n", .{}); break; } - + if (choice < 1 or choice > 4) { try stdout.print("Invalid choice. Please select 1-5.\\n", .{}); continue; } - + // Get numbers try stdout.print("Enter first number: ", .{}); _ = try stdin.readUntilDelimiterOrEof(&input_buf, '\n'); const num1 = std.fmt.parseFloat(f64, std.mem.trimRight(u8, &input_buf, "\n\r")) catch 0.0; - + try stdout.print("Enter second number: ", .{}); _ = try stdin.readUntilDelimiterOrEof(&input_buf, '\n'); const num2 = std.fmt.parseFloat(f64, std.mem.trimRight(u8, &input_buf, "\n\r")) catch 0.0; - + // Perform operation var result: f64 = 0.0; switch (choice) { @@ -252,7 +252,7 @@ pub fn main() !void { }, else => try stdout.print("Invalid operation\\n", .{}), } - + // Display result try stdout.print("Result: {d}\\n", .{result}); } diff --git a/lessons/zig/stage-4/level-2/lesson.md b/lessons/zig/stage-4/level-2/lesson.md index c1f20ba..c6e42f7 100644 --- a/lessons/zig/stage-4/level-2/lesson.md +++ b/lessons/zig/stage-4/level-2/lesson.md @@ -51,12 +51,12 @@ Build a complete Text Analysis Tool application that: ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` zig build-exe hello.zig ``` 2. **Run your program**: - ```bash + ``` ./hello hello ``` @@ -163,7 +163,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```zig +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/zig/stage-4/level-3/lesson.md b/lessons/zig/stage-4/level-3/lesson.md index f5e7480..653eb6b 100644 --- a/lessons/zig/stage-4/level-3/lesson.md +++ b/lessons/zig/stage-4/level-3/lesson.md @@ -51,12 +51,12 @@ Build a complete Data Processing application that: ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` zig build-exe hello.zig ``` 2. **Run your program**: - ```bash + ``` ./hello hello ``` @@ -163,7 +163,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```zig +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/zig/stage-4/level-4/lesson.md b/lessons/zig/stage-4/level-4/lesson.md index 130fea6..f7ddf3b 100644 --- a/lessons/zig/stage-4/level-4/lesson.md +++ b/lessons/zig/stage-4/level-4/lesson.md @@ -51,12 +51,12 @@ Build a complete File Operations application that: ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` zig build-exe hello.zig ``` 2. **Run your program**: - ```bash + ``` ./hello hello ``` @@ -163,7 +163,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```zig +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/zig/stage-4/level-5/lesson.md b/lessons/zig/stage-4/level-5/lesson.md index c3e3d59..b53e089 100644 --- a/lessons/zig/stage-4/level-5/lesson.md +++ b/lessons/zig/stage-4/level-5/lesson.md @@ -51,12 +51,12 @@ Build a complete API Integration application that: ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` zig build-exe hello.zig ``` 2. **Run your program**: - ```bash + ``` ./hello hello ``` @@ -163,7 +163,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```zig +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/zig/stage-4/level-6/lesson.md b/lessons/zig/stage-4/level-6/lesson.md index a0f2383..3fdbe77 100644 --- a/lessons/zig/stage-4/level-6/lesson.md +++ b/lessons/zig/stage-4/level-6/lesson.md @@ -51,12 +51,12 @@ Build a complete Database Operations application that: ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` zig build-exe hello.zig ``` 2. **Run your program**: - ```bash + ``` ./hello hello ``` @@ -163,7 +163,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```zig +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/zig/stage-4/level-7/lesson.md b/lessons/zig/stage-4/level-7/lesson.md index 59927aa..1426eb1 100644 --- a/lessons/zig/stage-4/level-7/lesson.md +++ b/lessons/zig/stage-4/level-7/lesson.md @@ -51,12 +51,12 @@ Build a complete Complete Application application that: ### How to Compile and Run 1. **Compile the code**: - ```bash + ``` zig build-exe hello.zig ``` 2. **Run your program**: - ```bash + ``` ./hello hello ``` @@ -163,7 +163,7 @@ A complete application has these components: 5. **Error Handling**: Manage problems gracefully **Code Organization:** -```zig +``` // Setup and initialization // Main program loop or flow // Helper functions diff --git a/lessons/zig/stage-5/level-1/lesson.md b/lessons/zig/stage-5/level-1/lesson.md index aa89ac2..c4f78f0 100644 --- a/lessons/zig/stage-5/level-1/lesson.md +++ b/lessons/zig/stage-5/level-1/lesson.md @@ -242,7 +242,7 @@ Follow these stages: **Your architecture will depend on your chosen project, but should include:** -```zig +``` // Main program structure // - Data definitions // - Core functions diff --git a/lessons/zig/stage-5/level-2/lesson.md b/lessons/zig/stage-5/level-2/lesson.md index 64005ad..70b290a 100644 --- a/lessons/zig/stage-5/level-2/lesson.md +++ b/lessons/zig/stage-5/level-2/lesson.md @@ -233,7 +233,7 @@ Follow these stages: **Your architecture will depend on your chosen project, but should include:** -```zig +``` // Main program structure // - Data definitions // - Core functions diff --git a/lessons/zig/stage-5/level-3/lesson.md b/lessons/zig/stage-5/level-3/lesson.md index 523245b..3814a77 100644 --- a/lessons/zig/stage-5/level-3/lesson.md +++ b/lessons/zig/stage-5/level-3/lesson.md @@ -238,7 +238,7 @@ Follow these stages: **Your architecture will depend on your chosen project, but should include:** -```zig +``` // Main program structure // - Data definitions // - Core functions diff --git a/lessons/zig/stage-5/level-4/lesson.md b/lessons/zig/stage-5/level-4/lesson.md index 1145032..814ae21 100644 --- a/lessons/zig/stage-5/level-4/lesson.md +++ b/lessons/zig/stage-5/level-4/lesson.md @@ -233,7 +233,7 @@ Follow these stages: **Your architecture will depend on your chosen project, but should include:** -```zig +``` // Main program structure // - Data definitions // - Core functions diff --git a/lessons/zig/stage-5/level-5/lesson.md b/lessons/zig/stage-5/level-5/lesson.md index 2223e0e..672646b 100644 --- a/lessons/zig/stage-5/level-5/lesson.md +++ b/lessons/zig/stage-5/level-5/lesson.md @@ -238,7 +238,7 @@ Follow these stages: **Your architecture will depend on your chosen project, but should include:** -```zig +``` // Main program structure // - Data definitions // - Core functions diff --git a/lessons/zig/stage-5/level-6/lesson.md b/lessons/zig/stage-5/level-6/lesson.md index 004b0d1..b93866f 100644 --- a/lessons/zig/stage-5/level-6/lesson.md +++ b/lessons/zig/stage-5/level-6/lesson.md @@ -232,7 +232,7 @@ Follow these stages: **Your architecture will depend on your chosen project, but should include:** -```zig +``` // Main program structure // - Data definitions // - Core functions diff --git a/lessons/zig/stage-5/level-7/lesson.md b/lessons/zig/stage-5/level-7/lesson.md index abb5b20..5ee8897 100644 --- a/lessons/zig/stage-5/level-7/lesson.md +++ b/lessons/zig/stage-5/level-7/lesson.md @@ -235,7 +235,7 @@ Follow these stages: **Your architecture will depend on your chosen project, but should include:** -```zig +``` // Main program structure // - Data definitions // - Core functions