Courses Practice Compete Upgrade to Pro Login Sign Up
All Blogs
Functions in C (Examples and
Practice)
2024-08-06 hrishik85
Table of Contents
1. Introduction
2. What are Functions in C?
3. Anatomy of a Function
4. Return Values
5. Parameters and Arguments
6. Variable Scope
7. Functions Within Functions
8. Predefined Functions
9. Useful Math Functions
10. Coding Tasks
11. Conclusion
Introduction
You might be wondering about functions - what they are and why they're important. Don't
worry, we've got you covered. Functions are like the building blocks of your program. They help
you break down big problems into smaller, more manageable parts. By the end of this post,
you'll understand how to use functions to make your code cleaner, more efficient, and easier to
read.
What are Functions in C?
Think of functions as small machines in a big factory. Each machine does one specific job. When
you put them all together, they can create something complex. In C programming, functions
work the same way.
Here's why functions are great:
They break down big programs into smaller, easier-to-handle parts
You can use them over and over again in different parts of your program
They make your code cleaner and easier to understand
Let's look at a simple example:
#include <stdio.h>
void greet() {
printf("Hello, welcome to C programming!\n");
}
int main() {
greet();
return 0;
}
In this example, greet() is a function that prints a welcome message. We can use it whenever
we want to say hello!
Anatomy of a Function
Now, let's break down the parts of a function. Every function in C has a specific structure:
return_type function_name(parameters) {
// Function body (code block)
return result; // Optional return statement
}
Let's look at each part:
1. return_type: This tells us what kind of data the function will give back. If it doesn't give
anything back, we use void.
2. function_name: This is the name we give our function. It should describe what the function
does.
3. parameters: These are inputs that the function can use.
4. Function body: This is where we write the code that does the actual work.
5. return: This sends a value back from the function (if needed).
Here's an example:
int add(int a, int b) {
int sum = a + b;
return sum;
}
This function is named add, it takes two int parameters, and it returns their sum.
Return Values
Functions in C can do two main things: return a value or print something.
When a function returns a value, it's like it's handing something back to the part of the program
that called it. Here's an example:
#include <stdio.h>
int calculate_square(int num) {
int square_result = num * num;
return square_result;
}
int main() {
int result = calculate_square(5);
printf("Square of 5: %d\n", result);
return 0;
}
This will output: Square of 5: 25
On the other hand, some functions just print something without returning a value. These
functions usually have a void return type:
#include <stdio.h>
void print_square(int num) {
int square_result = num * num;
printf("Square of %d is: %d\n", num, square_result);
}
int main() {
print_square(5);
return 0;
}
This will also output: Square of 5 is: 25
Try it on CodeChef
Parameters and Arguments
When we talk about functions, you'll often hear two terms: parameters and arguments. They're
related, but not quite the same:
Parameters are the variables listed in the function definition. They're like placeholders for the
values the function will use.
Arguments are the actual values we pass to the function when we call it.
Here's an example to make it clear:
#include <stdio.h>
int add_numbers(int a, int b) { // a and b are parameters
return a + b;
}
int main() {
int result = add_numbers(3, 5); // 3 and 5 are arguments
printf("Sum: %d\n", result);
return 0;
}
In this code, a and b are parameters, while 3 and 5 are arguments.
Try it on CodeChef
Variable Scope
In C, where you define a variable determines where you can use it. This is called "scope". There
are two main types of scope:
1. Global Scope: Variables defined outside of any function can be used anywhere in your
program.
#include <stdio.h>
int global_var = 10; // This is a global variable
void print_global() {
printf("%d\n", global_var); // We can use global_var here
}
int main() {
printf("%d\n", global_var); // We can also use global_var here
print_global();
return 0;
}
2. Local Scope: Variables defined inside a function can only be used within that function.
#include <stdio.h>
void my_function() {
int local_var = 20; // This is a local variable
printf("%d\n", local_var); // We can use local_var here
}
int main() {
// printf("%d\n", local_var); // This would cause an error
my_function();
return 0;
}
Remember, if a local variable has the same name as a global variable, the local variable will be
used within its function.
Try it on CodeChef
Functions Within Functions
In C, you can call one function from inside another function. This is really useful for breaking
down complex tasks. Here's an example:
#include <stdio.h>
int square(int a) {
return a * a;
}
int sum_of_squares(int a, int b) {
return square(a) + square(b);
}
int main() {
int result = sum_of_squares(3, 4);
printf("Sum of squares: %d\n", result);
return 0;
}
In this example, sum_of_squares calls square twice to calculate its result.
Predefined Functions
C comes with many built-in functions that you can use right away. These are called predefined
functions. Here are some common ones:
1. Input/Output Functions (from <stdio.h>):
printf(): Prints formatted output
scanf(): Reads formatted input
2. Math Functions (from <math.h>):
sqrt(): Calculates square root
pow(): Calculates power
3. String Functions (from <string.h>):
strlen(): Finds string length
strcpy(): Copies strings
To use these functions, you need to include the right header file at the top of your program.
Useful Math Functions
Let's look at some handy math functions you can use in your C programs. Remember to include
<math.h> to use these:
1. abs(x): Returns the absolute value of x
2. ceil(x): Rounds x up to the nearest integer
3. floor(x): Rounds x down to the nearest integer
4. pow(x, y): Returns x raised to the power of y
Here's a quick example:
#include <stdio.h>
#include <math.h>
int main() {
printf("Absolute value of -5: %d\n", abs(-5));
printf("Ceiling of 3.2: %.0f\n", ceil(3.2));
printf("Floor of 3.8: %.0f\n", floor(3.8));
printf("2 to the power of 3: %.0f\n", pow(2, 3));
return 0;
}
Coding Tasks
Now, let's put what we've learned into practice with some coding tasks!
Coding Task 1: Contest Ratings
Write a function that calculates how many new users will get a rating after a programming
contest.
Try it on CodeChef
Coding Task 2: Chessboard Cells
Create a function that determines the number of black cells on an n x n chessboard (where n is
even).
Try it on CodeChef
Coding Task 3: Debugging Practice
Debug a function that's supposed to calculate the difference between A+B and A*B.
Try it on CodeChef
Conclusion
We've covered the basics of creating and using functions, explored different types of functions,
and even tackled some practice problems.
Remember, mastering functions takes practice. Keep coding, experimenting, and solving
problems. As you become more comfortable with functions, you'll find that they make your code
more organized, reusable, and easier to understand. Best of luck and keep coding!
We have curated a set of MCQ and coding problems on Functions in C. These problems will help
you in solidifying your knowledge of Functions. Start solving these problems now!
You can also check our complete Learn C course if you want to learn C in the most fun and
engaging way possible.
Learning Courses Practice Paths Online Compilers Miscellaneous
Learn Python Practice Python Python online compiler Blogs
Learn JavaScript Practice JavaScript C online compiler CodeChef For Colleges
Learn C++ Practice C++ C++ online compiler Coding Contests
Learn C Practice C Java online compiler About Us
Learn Java Practice Java JavaScript online compiler Contact Us
More learning courses More practice paths More compilers Privacy Policy
www.codechef.com Follow Us