Create Functions in C

CCBeginner
Practice Now

Introduction

In this lab, you will learn how to create and use functions in C programming. The lab covers the fundamental concepts of declaring and defining functions, understanding function arguments, returning values from functions, handling void functions, and practicing function usage. You will explore these topics through hands-on examples and exercises, gaining the skills to write modular and reusable C code.

The lab starts by introducing the basics of function declaration and definition, demonstrating how to create and call simple functions. It then delves into the understanding of function arguments, showcasing how to pass different data types as input to functions. The lab also covers the concept of return values, guiding you on how to return data from functions. Additionally, the lab explores the usage of void functions, which do not return any values. Finally, you will have the opportunity to practice and apply the learned concepts through various exercises.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c(("`C`")) -.-> c/ControlFlowGroup(["`Control Flow`"]) c(("`C`")) -.-> c/FunctionsGroup(["`Functions`"]) c(("`C`")) -.-> c/BasicsGroup(["`Basics`"]) c/UserInteractionGroup -.-> c/output("`Output`") c/ControlFlowGroup -.-> c/switch("`Switch`") c/FunctionsGroup -.-> c/function_parameters("`Function Parameters`") c/FunctionsGroup -.-> c/function_declaration("`Function Declaration`") c/BasicsGroup -.-> c/variables("`Variables`") subgraph Lab Skills c/output -.-> lab-438257{{"`Create Functions in C`"}} c/switch -.-> lab-438257{{"`Create Functions in C`"}} c/function_parameters -.-> lab-438257{{"`Create Functions in C`"}} c/function_declaration -.-> lab-438257{{"`Create Functions in C`"}} c/variables -.-> lab-438257{{"`Create Functions in C`"}} end

Declare and Define Functions

In this step, you'll learn how to declare and define functions in C programming. Functions are fundamental building blocks that help organize and modularize your code.

Let's start by creating a new file called functions_demo.c in the ~/project directory:

cd ~/project
touch functions_demo.c

Now, let's write a simple function declaration and definition:

#include <stdio.h>

// Function declaration (prototype)
void greet(char* name);

// Main function
int main() {
    // Calling the function
    greet("LabEx User");
    return 0;
}

// Function definition
void greet(char* name) {
    printf("Hello, %s! Welcome to C programming.\n", name);
}

Let's break down the key components:

  • void greet(char* name) is the function declaration (prototype)
  • The function takes a character pointer (string) as an argument
  • void indicates the function doesn't return a value
  • Inside main(), we call the function with an argument
  • The function definition follows the main function, implementing the actual logic

Compile and run the program:

gcc functions_demo.c -o functions_demo
./functions_demo

Example output:

Hello, LabEx User! Welcome to C programming.

Functions help you:

  • Organize code into reusable blocks
  • Improve code readability
  • Reduce repetition
  • Modularize your program

Understand Function Arguments

In this step, you'll learn how to work with function arguments in C programming. Function arguments allow you to pass data into functions, making them more flexible and reusable.

Let's create a new file called function_arguments.c in the ~/project directory:

cd ~/project
touch function_arguments.c

Now, let's write a program demonstrating different types of function arguments:

#include <stdio.h>

// Function with multiple arguments
int calculate_rectangle_area(int length, int width) {
    return length * width;
}

// Function with a floating-point argument
float convert_celsius_to_fahrenheit(float celsius) {
    return (celsius * 9/5) + 32;
}

int main() {
    // Using integer arguments
    int length = 5;
    int width = 3;
    int area = calculate_rectangle_area(length, width);
    printf("Rectangle Area: %d square units\n", area);

    // Using floating-point argument
    float celsius = 25.0;
    float fahrenheit = convert_celsius_to_fahrenheit(celsius);
    printf("%.1f°C is %.1f°F\n", celsius, fahrenheit);

    return 0;
}

Let's break down the key concepts:

  • Functions can take multiple arguments of different types
  • calculate_rectangle_area() takes two integer arguments
  • convert_celsius_to_fahrenheit() takes a float argument
  • Arguments are passed by value in C (a copy is created)
  • The function can use these arguments in its calculation

Compile and run the program:

gcc function_arguments.c -o function_arguments
./function_arguments

Example output:

Rectangle Area: 15 square units
25.0°C is 77.0°F

Key points about function arguments:

  • Arguments provide input to functions
  • You can pass variables or direct values
  • The number and type of arguments must match the function declaration
  • Arguments help make functions more versatile and reusable

Return Values from Functions

In this step, you'll learn how to return values from functions in C programming. Return values allow functions to compute and send back results to the calling code.

Let's create a new file called function_returns.c in the ~/project directory:

cd ~/project
touch function_returns.c

Now, let's write a program demonstrating different types of return values:

#include <stdio.h>

// Function returning an integer
int square(int number) {
    return number * number;
}

// Function returning a float
float calculate_average(int a, int b, int c) {
    return (float)(a + b + c) / 3;
}

// Function returning a character
char get_grade(int score) {
    if (score >= 90) return 'A';
    else if (score >= 80) return 'B';
    else if (score >= 70) return 'C';
    else if (score >= 60) return 'D';
    else return 'F';
}

int main() {
    // Using integer return value
    int num = 7;
    int squared = square(num);
    printf("Square of %d is %d\n", num, squared);

    // Using float return value
    int math = 85, science = 92, english = 78;
    float average = calculate_average(math, science, english);
    printf("Average score: %.2f\n", average);

    // Using character return value
    int student_score = 85;
    char grade = get_grade(student_score);
    printf("Student score %d gets grade %c\n", student_score, grade);

    return 0;
}

Let's break down the key concepts:

  • Functions can return different data types
  • square() returns an integer result
  • calculate_average() returns a float
  • get_grade() returns a character
  • The return keyword sends a value back to the calling function
  • Return types must match the function declaration

Compile and run the program:

gcc function_returns.c -o function_returns
./function_returns

Example output:

Square of 7 is 49
Average score: 85.00
Student score 85 gets grade B

Key points about return values:

  • Return values allow functions to compute and send back results
  • Use appropriate return types based on the function's purpose
  • You can use return values directly or store them in variables
  • Return values make functions more powerful and flexible

Handle Void Functions

In this step, you'll learn about void functions in C programming. Void functions perform actions without returning a value, which is useful for tasks that don't need to send back a result.

Let's create a new file called void_functions.c in the ~/project directory:

cd ~/project
touch void_functions.c

Now, let's write a program demonstrating void functions:

#include <stdio.h>

// Void function to print a welcome message
void print_welcome() {
    printf("Welcome to the C Programming Lab!\n");
}

// Void function with parameters to display student information
void display_student_info(char* name, int age) {
    printf("Student Name: %s\n", name);
    printf("Student Age: %d\n", age);
}

// Void function to draw a simple pattern
void draw_pattern(int size) {
    for (int i = 0; i < size; i++) {
        for (int j = 0; j < size; j++) {
            printf("* ");
        }
        printf("\n");
    }
}

int main() {
    // Calling void functions
    print_welcome();

    // Void function with parameters
    char* student_name = "LabEx User";
    int student_age = 25;
    display_student_info(student_name, student_age);

    // Void function with a pattern
    int pattern_size = 3;
    printf("\nDrawing a %dx%d pattern:\n", pattern_size, pattern_size);
    draw_pattern(pattern_size);

    return 0;
}

Let's break down the key concepts:

  • Void functions have void as their return type
  • They perform actions without returning a value
  • print_welcome() simply prints a message
  • display_student_info() takes parameters and prints information
  • draw_pattern() creates a visual pattern using nested loops
  • Void functions are called like regular functions
  • You cannot use return with a value in void functions

Compile and run the program:

gcc void_functions.c -o void_functions
./void_functions

Example output:

Welcome to the C Programming Lab!
Student Name: LabEx User
Student Age: 25

Drawing a 3x3 pattern:
* * *
* * *
* * *

Key points about void functions:

  • Used for actions that don't need to return a value
  • Can take parameters
  • Useful for printing, logging, or performing specific tasks
  • Help organize and modularize code
  • Cannot return a value using return

Practice Function Usage

In this final step, you'll apply everything you've learned about functions in C by creating a comprehensive program that demonstrates multiple function types and usage.

Let's create a file called calculator.c in the ~/project directory:

cd ~/project
touch calculator.c

Now, let's write a program that implements a simple calculator with various functions:

#include <stdio.h>

// Function to add two numbers
int add(int a, int b) {
    return a + b;
}

// Function to subtract two numbers
int subtract(int a, int b) {
    return a - b;
}

// Function to multiply two numbers
int multiply(int a, int b) {
    return a * b;
}

// Function to divide two numbers with error handling
float divide(int a, int b) {
    if (b == 0) {
        printf("Error: Division by zero!\n");
        return 0;
    }
    return (float)a / b;
}

// Void function to display calculator menu
void display_menu() {
    printf("\n--- Simple Calculator ---\n");
    printf("1. Addition\n");
    printf("2. Subtraction\n");
    printf("3. Multiplication\n");
    printf("4. Division\n");
    printf("5. Exit\n");
    printf("Enter your choice: ");
}

int main() {
    int choice, num1, num2;
    float result;

    while (1) {
        display_menu();
        scanf("%d", &choice);

        // Exit condition
        if (choice == 5) {
            printf("Goodbye!\n");
            break;
        }

        // Validate choice
        if (choice < 1 || choice > 4) {
            printf("Invalid choice. Try again.\n");
            continue;
        }

        // Get user input
        printf("Enter two numbers: ");
        scanf("%d %d", &num1, &num2);

        // Perform calculation based on user choice
        switch (choice) {
            case 1:
                result = add(num1, num2);
                printf("Result: %d + %d = %d\n", num1, num2, (int)result);
                break;
            case 2:
                result = subtract(num1, num2);
                printf("Result: %d - %d = %d\n", num1, num2, (int)result);
                break;
            case 3:
                result = multiply(num1, num2);
                printf("Result: %d * %d = %d\n", num1, num2, (int)result);
                break;
            case 4:
                result = divide(num1, num2);
                printf("Result: %d / %d = %.2f\n", num1, num2, result);
                break;
        }
    }

    return 0;
}

Let's break down the key concepts:

  • Multiple function types are used (return values, void functions)
  • Functions perform specific mathematical operations
  • display_menu() is a void function showing the menu
  • Arithmetic functions return calculated results
  • The main() function implements a menu-driven calculator
  • Error handling is included for division by zero
  • switch statement used to select operation

Compile and run the program:

gcc calculator.c -o calculator
./calculator

Example interaction:

--- Simple Calculator ---
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
Enter your choice: 1
Enter two numbers: 10 5
Result: 10 + 5 = 15

--- Simple Calculator ---
...
Enter your choice: 5
Goodbye!

Key points about function usage:

  • Combine different function types
  • Use functions to break down complex problems
  • Implement error handling
  • Create modular and reusable code

Summary

In this lab, you learned how to declare and define functions in C programming, understand function arguments, return values from functions, handle void functions, and practice function usage. You started by creating a simple function to greet a user, and then explored more complex functions with multiple arguments and return values. You also learned how to use void functions and practice function usage in your programs. These fundamental concepts are essential for building modular and reusable code in C.

Other C Tutorials you may like