Lesson 7 in C Language: Functions! The Ultimate Tool to Say Goodbye to ‘Copy and Paste’!

Dear “Reboot Heroes”, after the training in the first six lessons, our program can: ✅ Speak, listen, remember, judge, and execute repeatedly. But I wonder if you have encountered this pain: “I have used this piece of code in several places, and I can only copy and paste it. If I change one place, I have to change all places!” For example, if we want to greet in multiple places: // At the beginning of the programprintf(“==========\n”);printf(“Welcome!\n”); printf(“==========\n”);// In the middle of the programprintf(“==========\n”);printf(“Welcome!\n”);printf(“==========\n”);// At the end of the programprintf(“==========\n”);printf(“Welcome!\n”);printf(“==========\n”); This is so silly! Programmers hate duplicate code! Today, we are going to introduce the “Copy and Paste Terminator” of the programming world – functions!
1. A function is like a “pre-made dish” in programming. Imagine this: every time you want to eat braised pork, you have to start from scratch, buy meat, cut it, and stir-fry the sugar… It’s too troublesome! The smart way is to standardize the method of making braised pork once, and then just heat it up whenever you want to eat! In programming:

  • The steps to make braised pork = function body
  • The name “braised pork” = function name
  • Heat it up to eat = call the function

2. How to define your first “pre-made dish”? (Defining a function) Syntax: ReturnType FunctionName(ParameterList) { // Function body – specific operations}
Scenario 1: Create a “greet” function #include <stdio.h>// Define greet functionvoid sayHello() { printf(“==========\n”); printf(“Welcome!\n”); printf(“==========\n”);}int main(){ printf(“Program starts…\n”); sayHello(); // Call function – just like heating up a pre-made dish printf(“Processing business logic…\n”); sayHello(); // Call again – another serving! printf(“Program ends\n”); return 0;}Interpretation:

  • void: return type, void means this function does not return anything
  • sayHello: function name, should be descriptive
  • () : parameter list, empty means no input needed
  • sayHello(): call the function, execute all the code in the function body

3. Functions with parameters: “Customized pre-made dishes” Sometimes we want more flexible functions: Scenario 2: Personalized greeting function #include <stdio.h>// Function with parametersvoid welcome(char name[], int age) { printf(“==========\n”); printf(“Welcome %s!\n”, name); printf(“Age: %d years\n”, age); printf(“==========\n”);}int main(){ welcome(“Alice”, 20); // Custom greeting for Alice welcome(“Bob”, 18); // Custom greeting for Bob return 0;}Output: ==========Welcome Alice!Age: 20 years==================== Welcome Bob!Age: 18 years==========4. Functions with return values: “Functions that produce results” Some functions need to return a result: Scenario 3: Addition function #include <stdio.h>// Function with return valueint add(int a, int b) { int result = a + b; return result; // Return calculation result}int main(){ int sum1 = add(5, 3); // Calculate 5+3 int sum2 = add(10, 20); // Calculate 10+20 printf(“5+3=%d\n”, sum1); printf(“10+20=%d\n”, sum2); printf(“Direct call: %d\n”, add(7, 8)); // Can also be used directly return 0;}5. Why use functions? Three major benefits! Benefit 1: Code reuse (write once, use everywhere) // Define function to check adulthoodint isAdult(int age) { return age >= 18;}int main(){ // Use in multiple places if (isAdult(20)) { printf(“Can enter\n”); } if (isAdult(15)) { printf(“Can enter\n”); } else { printf(“Access denied\n”); } return 0;}Benefit 2: Improve readability (self-explanatory code) // Poor writingif (score >= 90 && age < 30 && project_count > 5) { // Complex logic…}// Good writing if (isExcellent(score, age, project_count)) { // Clear logic…}Benefit 3: Easier debugging and maintenance If you need to modify the judgment logic, just change the function’s internal code, and all calling places will automatically take effect!
6. The “secret rules” of functions: 1. Declare before use: Functions must be defined before the main function, or declared first. 2. Parameter passing: Parameters are copies of values; modifying formal parameters does not affect actual parameters. 3. Return value: Can only return one value, but can return multiple values through pointers. Correct writing: #include <stdio.h>// Declare firstint multiply(int a, int b);int main(){ int result = multiply(3, 4); printf(“3×4=%d\n”, result); return 0;}// Define laterint multiply(int a, int b) { return a * b;}7. Ultimate creation: Smart Calculator Now, let’s use functions to create a truly practical tool! #include <stdio.h>// Function declarationsvoid showMenu();int add(int a, int b);int subtract(int a, int b);int multiply(int a, int b);float divide(int a, int b);int main(){ int choice, a, b; do { showMenu(); printf(“Please choose an operation (1-5):”); scanf(“%d”, &choice); if (choice >= 1 && choice <= 4) { printf(“Please enter two numbers:”); scanf(“%d %d”, &a, &b); } switch (choice) { case 1: printf(“Result: %d + %d = %d\n”, a, b, add(a, b)); break; case 2: printf(“Result: %d – %d = %d\n”, a, b, subtract(a, b)); break; case 3: printf(“Result: %d × %d = %d\n”, a, b, multiply(a, b)); break; case 4: if (b != 0) { printf(“Result: %d ÷ %d = %.2f\n”, a, b, divide(a, b)); } else { printf(“Error: Divisor cannot be 0!\n”); } break; case 5: printf(“Thank you for using! Goodbye!\n”); break; default: printf(“Invalid choice!\n”); } printf(“\n”); } while (choice != 5); return 0;}// Function definitionsvoid showMenu() { printf(“===== Smart Calculator =====\n”); printf(“1. Addition\n”); printf(“2. Subtraction\n”); printf(“3. Multiplication\n”); printf(“4. Division\n”); printf(“5. Exit\n”);}int add(int a, int b) { return a + b;}int subtract(int a, int b) { return a – b;}int multiply(int a, int b) { return a * b;}float divide(int a, int b) { return (float)a / b;}Interactive session: “Create a function to determine if a number is prime, and then test this function in the main function. Send the code and running screenshot to the backend to showcase your ‘function magic’!”

Leave a Comment