C Programming Cheat Sheet

CSE240 Homework 4 Concepts & Patterns

🧠 Programming Methodology

The Three-Step Process

1. INSTRUCTION
Read what the homework says to do
2. TRANSLATION
Convert requirement to C syntax
3. WHY
Understand the reasoning behind the choice
Key Insight: Instruction order ≠ Implementation order. Always think about logical flow, not comment order.

⚡ Essential Function Design Pattern

int myFunction() { // 1. VALIDATE INPUTS FIRST if (somethingWrong) { return errorCode; } // 2. PREPARE DATA convertInputsToProperFormats(); // 3. PERFORM MAIN OPERATION doTheActualWork(); // 4. CLEAN UP / ORGANIZE sortOrOrganizeResults(); // 5. REPORT SUCCESS return successCode; }
Remember: Always validate before doing work. Check conditions BEFORE attempting operations.

📊 Structs & Arrays of Structs

Basic Struct Syntax

struct studentRecord { char studentName[MAX_NAME_LENGTH]; char major[MAX_NAME_LENGTH]; schoolYear schoolYear; unsigned int studentID; }; // Create array of structs struct studentRecord list[MAX_STUDENTS];

Accessing Struct Elements

// Access elements using dot notation list[i].studentName list[i].major list[i].schoolYear list[i].studentID // Copy strings into struct strcpy(list[count].studentName, studentName_input); // Assign direct values list[count].studentID = studentID_input;

🔢 Enums (Enumeration Types)

typedef enum { freshman = 0, sophomore, junior, senior } schoolYear;

String to Enum Conversion

schoolYear yearEnum; if (strcmp(schoolYear_input, "freshman") == 0) { yearEnum = freshman; } else if (strcmp(schoolYear_input, "sophomore") == 0) { yearEnum = sophomore; } // ... etc

Enum to String Conversion

switch (list[i].schoolYear) { case freshman: printf("freshman\n"); break; case sophomore: printf("sophomore\n"); break; // ... etc }

🔤 String Operations

✅ CORRECT

// Compare strings if (strcmp(str1, str2) == 0) { // strings are equal } // Copy strings strcpy(destination, source);

❌ WRONG

// Can't use == with strings! if (str1 == str2) { // This compares addresses! } // Can't assign strings directly! destination = source;

strcmp() Return Values

🔄 Loop Patterns

Basic Array Traversal

// Loop through all existing elements for (int i = 0; i < count; i++) { // Process list[i] }

Bubble Sort Pattern

// Nested loops for bubble sort for (int i = 0; i < count - 1; i++) { for (int j = 0; j < count - 1 - i; j++) { if (strcmp(list[j].studentName, list[j + 1].studentName) > 0) { // Swap using temp variable temp = list[j]; list[j] = list[j + 1]; list[j + 1] = temp; } } }
Why count - 1? If you have 5 elements, you only need 4 comparisons (pairs: 0-1, 1-2, 2-3, 3-4)

✅ Input Validation Patterns

Essential Validation Checks

// 1. Check if array/list is full if (count >= MAX_STUDENTS) { return 2; // or appropriate error code } // 2. Check for duplicates for (int i = 0; i < count; i++) { if (strcmp(list[i].name, newName) == 0) { return 0; // duplicate found } } // 3. Check if list is empty (for display functions) if (count == 0) { printf("List is empty.\n"); return; }

📁 File I/O Patterns

Reading Files

FILE* file; file = fopen(fileName, "rb"); // "rb" = read binary // Always check if file exists! if (file == NULL) { printf("%s not found\n", fileName); return; } // Read data in same order it was saved fread(&count, sizeof(count), 1, file); fclose(file);

Writing Files

FILE* file; file = fopen(fileName, "wb"); // "wb" = write binary // Save data in specific order fwrite(&count, sizeof(count), 1, file); fclose(file);
Critical: Read and write data in the EXACT same order, or your program will crash!

🎯 Common Return Value Patterns

// Standard return codes for add functions return 0; // Error: item already exists return 1; // Success: item added return 2; // Error: list is full

How Calling Functions Use Return Values

int result = addSort(name, major, year, id); if (result == 0) printf("Student is already on the list!\n"); else if (result == 1) printf("Student successfully added!\n"); else printf("Unable to add. List is full!\n");

💡 Key Programming Insights

⚠️ Common Mistakes to Avoid

❌ Don't Do This

  • Use == to compare strings
  • Assign strings with = operator
  • Forget to check if list is full
  • Try to add before validating
  • Use count as loop limit when it can change
  • Forget to increment count after adding

✅ Do This Instead

  • Use strcmp() for string comparison
  • Use strcpy() for string copying
  • Check count >= MAX_SIZE first
  • Validate all inputs before processing
  • Use count-1 for loop limits
  • Always count++ after successful add

Keep this cheat sheet handy for future C programming assignments!

Remember: Validate → Prepare → Process → Organize → Return