C Operators
C Operators
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Bitwise operators
5. Assignment operators
6. Conditional operators
7. Special operators
Let's understand each one of these operator types, one by one with working code examples.
What is an Operand?
For example, when we say 4+5, numbers 4 and 5 are operands whereas + is an operator.
Different operators work with different numbers of operands like the + operator requires
two operands or values, the increment operator ++ requires a single operand.
1. Arithmetic Operators in C
The following table shows all the basic arithmetic operators along with their descriptions.
Example
Operato
Description (where a and b are variables with
r
some integer value)
To learn in what order the arithmetic operators are executed, visit C Operator Precedence.
Let's see a code example to understand the use of the basic arithmetic operators in C programs.
#include <stdio.h>
int main() {
// addition
result = a+b;
// subtraction
result = a-b;
// multiplication
result = a*b;
result = a/b;
return 0;
Addition of a & b = 73
Subtraction of a & b = 27
Division of a & b = 2
The modulus operator returns the remainder value after the division of the provided values.
#include <stdio.h>
int main() {
result = a%b;
printf("result = %d",result);
return 0;
result = 3
The decrement operator is used to decrease the value of any numeric value by 1.
#include <stdio.h>
int main() {
/*
*/
/*
*/
return 0;
Incrementing value of a = 11
Decrementing value of b = 19
Decrementing value of a = 11
Value of a = 10
Incrementing value of b = 19
Value of b = 20
In the code example above, we have used the increment operator as ++a and b++, while the
decrement operator as --b and a--.
When we use the increment and decrement operator as a prefix (means before the
operand), then, first the increment operation is done and that value is used, like in the first
two printf() functions, we get the updated values of a and b.
Whereas when we use the increment and decrement operators as postfix (means after the
operand), then, first the larger expression is evaluated which is printf() in this case and then
the value of the operand is updated.
2. Relational operators in C
The relational operators (or comparison operators) are used to check the relationship
between two operands.
It checks whether two operands are equal or not equal or less than or greater than, etc.
For example, if we have two numbers 14 and 7, if we say 14 is greater than 7, this is true,
hence this check will return 1 as the result with relationship operators.
On the other hand, if we say 14 is less than 7, this is false, hence it will return 0.
The following table shows all relational operators supported in the C language.
Operato Example
Description
r (a and b, where a = 10 and b = 11)
< Check operand on the left is smaller than the right operand a < b, returns 1
>= check left operand is greater than or equal to the right a >= b, returns 0
Operato Example
Description
r (a and b, where a = 10 and b = 11)
operand
To learn in what order the relational operators are executed, visit C Operator Precedence.
When we use relational operators, we get the output based on the result of the comparison.
If it's true, then the output is 1 and if it's false, then the output is 0.
#include <stdio.h>
int main() {
// Equal
result = (a==b);
printf("(a == b) = %d \n",result);
// less than
result = (a<b);
// greater than
result = (a>b);
result = (a<=b);
return 0;
(a == b) = 0
(a < b) = 1
(a > b) = 0
(a <= b) = 1
In the code example above, a has a value 10, and b has a value 20, and then different comparisons
are done between them.
In the C language, true is any value other than zero. And false is zero.
3. Logical Operators in C
Example
Operator Description
(a and b, where a = 1 and b = 0)
|| Logical OR a || b, returns 1
These operators are used to perform logical operations and are used with conditional statements
like C if-else statements.
1. With the AND operator, only if both operands are true, the result is true.
2. With the OR operator, if a single operand is true, then the result will be true.
#include <stdio.h>
int main() {
int a = 1, b = 0, result;
// And
// Or
result = (a || b);
printf("a || b = %d \n",result);
// Not
result = !a;
printf("!a = %d \n",result);
return 0;
(a && b) = 0
(a || b) = 1
(!a) = 0
4. Bitwise Operators in C
These operators also perform the shifting of bits from right to left.
Bitwise operators are not applied to float or double, long double, void, etc. (Learn about C
float and double datatype).
Operator Description
| Bitwise OR
The bitwise AND, OR, and NOT operator works the same way as the Logical AND, OR, and NOT
operators, except that the bitwise operators work bit by bit.
Below we have a truth table for showing how these operators work with different values.
0 0 0 0 0
a b a&b a|b a^b
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
Bitwise operators can produce any arbitrary value as a result. It is not mandatory that the result will
either be 0 or 1.
The bitwise shift operator shifts the bit value, either to the left or right.
The left operand specifies the value to be shifted and the right operand specifies
the number of positions that the bits in the value have to be shifted.
Understand, how bits shift from left to right and vice versa.
a = 00010000
b=2
a << b = 01000000
a >> b = 00000100
In case of a << b, 2 bits are shifted to left in 00010000 and additional zeros are added to the opposite
end, that is right, hence the value becomes 01000000
And for a >> b, 2 bits are shifted from the right, hence two zeros are removed from the right and two
are added on the left, hence the value becomes 00000100
Please note, shift doesn't work like rotating, which means, the bits shifted are not added at the other
end. The bits that are shifted are lost.
The one's complement operator will change all the 1's in the operand to 0, and all the 0's are set to
1.
For example, if the original byte is 00101100, then after one's complement it will become 11010011.
#include <stdio.h>
int main() {
int a = 0001000, b = 2, result;
// <<
result = a<<b;
printf("a << b = %d \n",result);
// >>
result = a>>b;
printf("a >> b = %d \n",result);
return 0;
}
a << b = 2048
a >> b = 128
5. Assignment Operators in C
For example, if we want to assign a value 10 to a variable x then we can do this by using the
assignment operator like: x = 10; Here, = (equal to) operator is used to assign the value.
In the C language, the = (equal to) operator is used for assignment however it has several
other variants such as +=, -= to combine two operations in a single statement.
You can see all the assignment operators in the table given below.
Example
Operator Description (a and b are two variables, with
where a=10 and b=5)
adds right operand to the left operand and assign the a+=b, is same as a=a+b, value
+=
result to left operand of a becomes 15
subtracts right operand from the left operand and a-=b, is same as a=a-b, value
-=
assign the result to left operand of a becomes 5
mutiply left operand with the right operand and assign a*=b, is same as a=a*b, value
*=
the result to left operand of a becomes 50
/= divides left operand with the right operand and assign a/=b, is same as a=a/b, value
the result to left operand of a becomes 2
Example
Operator Description (a and b are two variables, with
where a=10 and b=5)
calculate modulus using two operands and assign the a%=b, is same as a=a%b, value
%=
result to left operand of a becomes 0
When we combine the arithmetic operators with the assignment operator =, then we get
the shorthand form of all the arthmetic operators.
Below we have a code example in which we have used all the different forms of assignment
operators, starting from the basic assignment.
#include <stdio.h>
int main() {
int a = 10;
// Assign
int result = a;
printf("result = %d \n",result);
// += operator
result += a;
printf("result = %d \n",result);
// -= operator
result -= a;
printf("result = %d \n",result);
// *= operator
result *= a;
printf("result = %d \n",result);
return 0;
OUTPUT:
result = 10
result = 20
result = 10
result = 100
The ternary operator, also known as the conditional operator in the C language can be used for
statements of the form if-then-else.
The first expression (expression 1) returns either true or false, based on which it is decided
whether (expression 2) will be executed or (expression 3)
If (expression 1) returns false then the expression on the right side of : i.e (expression 3) is
executed.
#include <stdio.h>
int main() {
*/
result = (a==b)?(a+b):(a-b);
printf("result = %d",result);
return 0;
result = 40
Apart from arithmetic, relational, logical, assignment, etc. operators, C language uses some other
operators such as:
1. sizeof operator
2. & operator
3. * operator
5. [] operator, etc.
sizeof to find size of any entity(variable, array, etc.), & operator to find the address of a variable, etc.
You can see a list of such operators in the below table.
. (dot) used to access individual elements of If emp is a structure with an element int age in it,
operator a C structure or C union. then [Link] will return the value of age.
We will learn about *, dot operator, arrow operator and [] operator as we move on in this tutorial
series, for now, let's see how to use the sizeof and & operators.
Here is a code example, try running in the live code compiler using the Run code button.
#include <stdio.h>
int main() {
int a = 20;
char b = 'B';
double c = 17349494.249324;
// sizeof operator
// & operator
return 0;
OUTPUT:
Size of a is: 4
Size of b is: 1
Size of c is: 8
Reverse a number
For Loop in C
29 Jun 2025 | 9 min read
In C programming language, the for loop is used to iterate a task for a specific number of times. If the
number of iterations is fixed, we can use the for loop instead of the while or do-while loop. It consists
of three parts: initialization, condition, and increment or decrement.
Syntax
2. {
4. }
In this syntax,
o Initialization: It is used to set the loop variable before it starts (e.g., int count = 1;). It just
runs once.
o Condition:The condition statement checks the given condition. If the condition is true, it
executes the of for loop. If the condition is false, it terminates the for loop.
o Update (Increment/Decrement): After execution of each loop, it adjusts the loop variable
(e.g., count++) to help it reach the stopping point.
o Loop Body: It represents the loop of the body. It continues to run as long as the condition
holds true.
Step 1: First, go to the for loop and initialize the variables and their values.
o If the condition is false, it terminates the loop body and moves to the next iteration.
Step 4: After that, it proceeds to the update expression, where the value is increased or decreased by
1, and then it goes to step 3 to check the condition.
Step 5: At the end, it exits from the loop and prints the output.
Let us take a simple example to illustrate the displaying numbers from 1 to 5 using a for loop in C
language.
Example
1. #include <stdio.h>
5. {
7. }
8. return 0;
9. }
Output:
Explanation:
In this example, we use a for loop to print numbers 1 to 5. After that, the loop begins with count = 1
and increases by 1 with each iteration, which shows the current value with a message until the count
reaches 5.
Let us take a simple example to illustrate the Printing Even Numbers between 2 and 10 using a for
loop in C language.
Example
1. #include <stdio.h>
3. {
5. {
7. }
8. return 0;
9. }
Output:
Explanation:
In this example, we generate even numbers between 2 and 10 using the for loop. The loop starts at 2
and increments by 2 with each iteration, printing the current value as an even number until it
reaches 10.
In C programming language, a nested for loop is defined as one for loop inside another for loop.
Every time the outer loop is executed, the inner loop is fully executed. This structure is particularly
effective for working with two-dimensional data, generating patterns, or conducting routine tasks in
a systematic manner.
Syntax
4. }
6. }
o The outer loop should be used to regulate the primary sequence (for example, rows in a
matrix).
o In order to accommodate sub-iterations, place the inner loop inside the outer loop (for
example, columns).
o Set the correct initialization, condition, and update expressions for both loops.
o Add the logic that we want to run inside the inner loop's body.
Let us take a simple example to illustrate the Nested for loop in C language.
Example
1. #include <stdio.h>
3. {
4. int rows = 7;
6. {
7. for (int col_num = 1; col_num <= row_num; col_num++)
8. {
10. }
11. printf("\n");
12. }
13. return 0;
14. }
Output:
12
123
1234
12345
123456
1234567
Explanation:
In this example, we print a right-angled triangle of numbers with the help of a nested for loop. For
each row from 1 to 7, it prints numbers from 1 to the current row number, which generates an
incremental number pattern.
Let us take a simple example to illustrate printing the Star Pattern for Right-Angled Triangle using
nested for loop in C language.
Example
1. #include <stdio.h>
3. {
5. {
7. {
8. printf("*");
9. }
10. printf("\n");
11. }
12. return 0;
13. }
Output:
**
***
****
*****
Explanation:
In this example, we generate a right-angled triangle pattern via a nested for loop. The outer loop
specifies the number of lines, while the inner loop prints rising stars (*) on each line to form the
triangular shape.
Jumping statements:
C programming language allows jumping from one statement to another. It also supports break,
continue, return and go to jump statements.
Break :
It is a keyword which is used to terminate the loop (or) exit from the block.
The control jumps to next statement after the loop (or) block.
When break is used in nested loops then, only the innermost loop is terminated.
Example
Void main( ) {
int i;
for (i=1; i<=5; i++)
{
printf ("%d", i);
if (i==3)
break;
}
}
Output
123
Continue :
The continue statement in C is a jump statement used to skip the current iteration of a loop and
continue with the next iteration. It is used inside loops (for, while, or do-while) along with the
conditional statements to bypass the remaining statements in the current iteration and move on to
the next iteration.
Example:
#include<stdio.h>
Void main( )
int i;
if (i==2)
continue;
printf("%d", i);
Output
1 345
Return :
It terminates the execution of function and returns the control of calling function
return[expression/value];
Example
#include<stdio.h>
int value();
void main()
int a;
a=value();
int value()
int b=5;
return b;
Output
goto :
It is used after the normal sequence of program execution by transferring the control to some other
part of program.
#include<stdio.h>
Void main( )
printf("Hello");
goto aditya;
aditya: printf("welcome");
Output
Hello welcome
C Arrays
In C programming, an array is defined as the collection of
similar types of data items stored at contiguous memory
locations.
Arrays are the derived data type in C programming language
that can store the primitive type of data, such as int, char,
double, float, etc.
It also has the capability to store the collection of derived
data types, such as pointers, structure, etc.
The array is the simplest data structure where each data
element can be randomly accessed by using its index number.
Example
1. #include<stdio.h>
2. int main(){ //main function
3. int i=0,j=0;
4. int a[4]={10,20,30,40}; //declaration & initialization
5. int marks[5];//declaration of array
6. marks[0]=80;//initialization of array
7. marks[1]=60;
8. marks[2]=70;
9. marks[3]=85;
10. marks[4]=75;
11. //traversal of array
12. for(i=0;i<5;i++){
13. printf("%d \n",marks[i]); }
14. for(j=0;j<4;j++){
15. printf("%d \n",a[j]);
16. }//end of for loop
17. return 0;
18. }
Output:
80
60
70
85
75
Explanation:
In this example, we declare an integer array of marks of size
5. Each element is initialized individually with values like 80,
60, 70, etc. A for loop is employed to loop through the array
from index position 0 to 4 and print out the value using printf.
C Array Declaration with Initialization Example
Let's take an example to illustrate how to declare and
initialize the array at the time of declaration in C.
Example
1. #include<stdio.h>
2. int main(){ //main function
3. int i=0;
4. int marks[5]={20,30,40,50,60};//declaration and initializ
ation of array
5. //traversal of array
6. for(i=0;i<5;i++){
7. printf("%d \n",marks[i]);
8. }
9. return 0;
10. }
Output:
20
30
40
50
60
Explanation:
In this example, we define and initialize a five-element
integer array mark with values 20, 30, 40, 50, and 60. After
that, we use a for loop to iterate over the array from index 0
through 4, which prints each of its elements using printf.
Accessing Array Elements
In C programming, array supports random access to its
element, i.e., we can access any element of the array by
giving the position of the element, referred to as the index.
The values of the index begin from 0 and proceed up to
array_size-1. We supply the index within square brackets []
followed by the name of the array.
Syntax
It has the following syntax:
1. array_name [index];
Where, the index value lies into this range - (0 ≤ index ≤ size-
1).
C Example to Access Array Elements
Let us take an example to illustrate how to access array
elements in C.
Example
1. #include <stdio.h>
2. int main() { //main function
3. int numbers[4] = {10, 20, 30, 40};
4. printf("Accessing array elements:\n");
5. printf("Element at index 0: %d\n", numbers[0]);
6. printf("Element at index 1: %d\n", numbers[1]);
7. printf("Element at index 2: %d\n", numbers[2]);
8. printf("Element at index 3: %d\n", numbers[3]);
9. return 0;
10. }
Output:
Accessing array elements:
Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Explanation:
In this example, we consist of the standard input-output
library and a definition of the main function. It has an integer
array numbers of size 4 with initial values 10, 20, 30, and 40.
After that, it prints every element using printf by addressing
them using their index from 0 to 3. The program terminates
by returning 0, which shows the successful program
execution.
Updating the Array Element
In C, we can change the value of array elements at index i
quite the same way we access an element using the array
square brackets [] and assignment operator (=).
Syntax
It has the following syntax:
1. array_name[i] = new_value;
C Example to Update the Array Elements
Let us take an example to illustrate how to update the array
elements in C.
Example
1. #include <stdio.h>
2. int main() { //main function
3. int numbers[5] = {5, 10, 15, 20, 25};
4. printf("Original value at index 2: %d\n", numbers[2]);
5. numbers[2] = 99;
6. printf("Updated value at index 2: %d\n", numbers[2]);
7. return 0;
8. }
Output:
Original value at index 2: 15
Updated value at index 2: 99
Explanation:
In this example, we declare an integer array of numbers of
size 5. Next. it prints the initial value at index 2, which is 15.
After that, it modifies the value at index 2 to 99 via
assignment (numbers[2] = 99;) and prints the modified value.
Array Traversal
In C, array traversal is the operation that allows us to travel
through each element of the array in a particular sequence.
In C array traversal, we use loops to access each element of
the array.
C Array Traversal Example
Let us take an example to illustrate the array traversal in C.
Example
1. #include <stdio.h>
2. int main() { //main function
3. int numbers[5] = {2, 4, 6, 8, 10};
4. printf("Traversing the array:\n");
5. for (int i = 0; i < 5; i++) {
6. printf("Element at index %d: %d\n", i, numbers[i]);
7. }
8. return 0;
9. }
Output:
Traversing the array:
Element at index 0: 2
Element at index 1: 4
Element at index 2: 6
Element at index 3: 8
Element at index 4: 10
Explanation:
In this example, we initialize an integer array of numbers of
size 5 containing the elements 2, 4, 6, 8, and 10. It employs a
for loop from index 0 to 4 to iterate through the array. Within
the loop, printf is employed to output the index and the
respective array element. The program terminates by
returning 0.
Size of Array
The size of the array is the number of elements stored in the
array. We can get the size using the sizeof() operator.
o The sizeof() operator gives the size in bytes. sizeof(arr)
gives the total bytes of the array.
o Each element in an array is of type int, which has a size
of 4 bytes. Therefore, we can find the size of the array by
dividing the total size in bytes by the byte size of a single
element.
C Size of Array Example
Let us take an example to illustrate the size of array in C.
Example
1. #include <stdio.h>
2. int main() { //main function
3. int numbers[] = {10, 20, 30, 40, 50};
4. int size = sizeof(numbers) / sizeof(numbers[0]);
5. printf("Size of the array: %d\n", size);
6. return 0;
7. }
Output:
Size of the array: 5
Explanation:
In this example, we declare an integer array of numbers of
size 5. After that, it calculates the number of elements by
dividing the overall memory size of the array
(sizeof(numbers)) by the memory size of a single element
(sizeof(numbers[0])). The value is assigned to the variable size
and printed.
Two-Dimensional Array in C
A Two-Dimensional array, or 2D array in C, is an array
possessing precisely two dimensions. It can be thought of as
rows and columns arranged in a two-dimensional plane.
Syntax
It has the following syntax:
1. return_type array_name[size1] [size2] .. [sizen];
2-Dimensional Example in C
Let us take an example to illustrate the 2-Dimensional Array
in C.
Example
1. #include <stdio.h>
2. int main() { //main function
3. int matrix[2][3];
4. Int i,j;
5. int value = 1;
6. for (i = 0; i < 2; i++) {
7. for (j = 0; j < 3; j++) {
8. matrix[i][j] = value;
9. value++;
10. }
11. }
12. printf("2D Array:\n");
13. for (i = 0; i < 2; i++) {
14. for (j = 0; j < 3; j++) {
15. printf("%d ", matrix[i][j]);
16. }
17. printf("\n");
18. }
19. return 0;
20. }
Output:
2D Array:
123
456
Explanation:
In this example, we declare a 2D integer array matrix of size 2
rows and 3 columns. An integer variable value is set to 1. In
nested for loops, each of the array elements is assigned
numbers from 1 to 6 in increasing order. After that, the outer
loop works for rows, and the inner loop for columns. Once
initialized, another pair of nested loops is used to print the
array in column-row order.
Three-Dimensional Array in C
In C, another common type of multi-dimensional array is a
Three-Dimensional Array or 3D Array. A 3D array has precisely
three dimensions. It is imagined as a group of 2D arrays
placed upon one another to form the third dimension.
3-Dimensional Array Example
Let us take an example to illustrate the 3-Dimensional array in
C.
Example
1. #include <stdio.h>
2. int main() { //main function
3. int arr[2][2][3];
4. int i,j,k;
5. int value = 1;
6. for (i = 0; i < 2; i++) {
7. for (j = 0; j < 2; j++) {
8. for (k = 0; k < 3; k++) {
9. arr[i][j][k] = value;
10. value++;
11. }
12. }
13. }
14. printf("3D Array Elements:\n");
15. for (i = 0; i < 2; i++) {
16. printf("Block %d:\n", i);
17. for ( j = 0; j < 2; j++) {
18. for ( k = 0; k < 3; k++) {
19. printf("%d ", arr[i][j][k]);
20. }
21. printf("\n");
22. }
23. printf("\n");
24. }
25. return 0;
26. }
Output:
3D Array Elements:
Block 0:
123
456
Block 1:
789
10 11 12
Explanation:
In this example, we declare a 3D array arr[2][2][3], i.e., it has
2 blocks, each containing 2 rows and 3 columns. A variable
value is set to 1 and is used to initialize each element of the
array with three nested for loops. The outer loop traverses
blocks, the middle loop traverses rows, and the innermost
loop traverses columns.
C Functions
In C programming, a function is a block of code that can perform a specific task. It consists of a set of
programming statements that is enclosed by curly braces {}. A function can be called multiple times
to provide reusability and modularity to the C program. In other words, we can say that the
collection of functions creates a program. The function is also known as procedure or subroutine in
other programming languages.
Here, we will see how we can define and declare the functions in C.
Function Declaration
In C programming, a function declaration gives details about a function's name, parameters, and
return type, allowing the compiler to make use of the information before it is defined. It ensures that
function calls are valid and type-safe even if the function is defined later in the program.
1. return_type function_name(parameter_list);
In this syntax;
o return_type: It represents the return type, such as int, char, double, string, void, etc.
1. int add(int a, int b); // Declaring a function that returns an int and takes two int argumen
ts
Function Definition
In C programming, a function definition provides the actual body of the function, which means the
block of code that performs a specific task. It informs the compiler what the function does when it is
called. Unlike a function declaration, the definition includes the implementation.
2. {
3. return a + b;
4. }
Function Call
In C programming, a function call is a way of using a function by giving its name and necessary
arguments. When the function is called, the control goes to the code that has been written within
the definition of that function, and then the output is returned. It enables code reuse and modular
programming in C, resulting in better organization.
Syntax for Function Call
1. function_name(actual_arguments);
1. int result = add(5, 10); // Calling the function and storing result
Example
1. #include <stdio.h>
2. // Function Declaration
3. int multiply(int, int);
4. int main() { //main function
5. int result, a=2,b=3;
6. // Calling the function
7. result=multiply(a,b);
8. Printf(“%d”,result);
9. return 0; }
10. int multiply(int a, int b)
11. {
12. int c=a*b;
13. return c;
14. }
[Link] Header file Description
1 stdio.h It is a standard
input/output
header file. It
contains all the
library functions
regarding
standard
input/output.
2 conio.h It is a console
input/output
header file.
8 stdarg.h Variable
argument
functions are
defined in this
header file.
15. result = multiply(4, 5);
16.
18. return 0;
19. }
20.
23. return a * b;
24. }
Output:
Explanation:
In this example, we demonstrate the use of a function declaration, definition, and call. We have
taken the multiply function that takes two integers as arguments, multiplies them, and returns the
result. After that, the main() function calls the user-defined function and prints the product.
A C function's return type indicates the value that, after execution, will be sent back to the caller. It
informs the compiler about the output type char, float, and int that the function will generate.
Types of Functions in C
There are mainly two types of functions in C programming. These are as follows:
1) Library Functions
Library functions are the inbuilt functions in C that are grouped and placed in a common place called
the library. Such functions are used to perform some specific operations. For example, printf is a
library function used to print on the console. The library functions are created by the designers of
compilers. All C standard library functions are defined inside the different header files saved with the
extension .h.
We need to include these header files in our program to make use of the library functions defined in
such header files. For example, in order to use the library functions, such as printf/scanf, we need to
include stdio.h in our program, which is a header file that contains all the library functions regarding
standard input/output. Library Functions are the built-in functions that are mainly declared in the C
header files, such as scanf(), printf(), gets(), puts(), ceil(), floor(), etc.
The list of mostly used header files is given in the following table.
o In regard to string manipulation, library files had specific rules that defined what should be
included at the beginning of each code, such as <stdio.h>, <math.h>, or <string.h>.
o Examples of Use:
o In mathematics, the functions ceil() and floor() are used to round integers.
Let us take an example to illustrate the library function in C using the sqrt() function.
Example
1. #include <stdio.h>
5. double result;
6.
8. result = sqrt(num);
9.
11. return 0;
12. }
Output:
Explanation:
In this example, we demonstrate the use of the library function sqrt() from the math.h header to
calculate the square root of a number. After that, the variable num is set to 169.0, and sqrt(num)
returns its square root, which is then printed using the printf() function.
2) User Defined Functions in C
In C programming, user-defined functions are the functions that are created by the C programmer so
that the user can use them many times. It reduces the complexity of a big program and optimizes the
code.
o Logic encapsulation through user-defined functions helps improve modularity and system
scalability because code blocks that have similarities can be stored in a single name
container.
o There is less risk for errors, which helps to improve maintainability because changes in logic
can be made containing a single function instead of multiple parts throughout the code.
o Controlling the function's name, scope, and behavior is useful for avoiding conflicts and
tailoring logic to specific requirements.
o "Recursiveness" is the capacity of user-defined functions to call themselves. This capacity can
be used to solve tree traversal, Fibonacci, and factorial challenges.
Example
1. #include <stdio.h>
3. void temp();
4. int main() {
5. // Function call
6. tpoint();
7. return 0;
8. }
12. }
Output:
In this example, we define a user-defined function named tpoint() that prints a welcome message.
After that, the function is declared before the main() function, called inside main() function, and
defined afterward. When executed, it displays the output.
Several differences between library functions and user defined functions in C are as follows:
A function may or may not accept any argument. It may or may not return any value. Based on these
facts, there are four different aspects of function calls.
In C programming, this type of function neither accepts nor returns any input parameters. It is
usually applied when the function finishes a task that doesn't need any extra data or results to be
returned to the caller function. It is a completely independent logic. These functions, which are
usually called from the main() function, can either print messages or carry out predefined actions.
Let us take an example to illustrate the function without arguments and without return value in C.
Example
1. #include<stdio.h>
2. void printName();
3. void main ()
4. {
5. printf("Hello ");
6. printName();
7. }
8. void printName()
9. {
10. printf("TpointTech");
11. }
Output:
Hello TpointTech
Explanation:
In this example, we demonstrate a user-defined function printName() that prints "TpointTech". In the
main() function, "Hello " is printed first, followed by a call to printName() function, which completes
the output. The final output is: Hello TpointTech.
In C programming, this approach does not take any arguments. It also returns a value to the caller.
Let us take an example to illustrate the function without arguments and without return value in C.
Example
1. #include <stdio.h>
2.
4. return 100;
5. }
6.
7. int main() {
11. }
Output:
Explanation:
In this example, we define a function getNumber() that takes no arguments and returns the integer
100. In the main() function, the returned value is stored in the variable num and printed.
In C programming, this type of function accepts parameters but does not return a value. It performs
several operations using the inputs and may display the result directly. Such functions are useful
when a task requires to be executed based on inputs without sending a result back to the caller.
Let us take an example to illustrate the Function with arguments and without return value in C.
Example
1. #include<stdio.h>
3. void main()
4. {
5. int a,b,result;
8. scanf("%d %d",&a,&b);
9. sum(a,b);
10. }
12. {
14. }
Output:
The sum is 46
Explanation:
In this example, we define a function sum(int, int) that takes two arguments and prints their sum. In
the main() function, the user enters two numbers, which are passed to the function. The function
calculates and directly displays the result without returning it.
In C programming, it is the most popular and adaptable design. The function takes inputs in addition
to returning a result. Functions that have to manage input data and send back the result to the caller
code are best for it. As it promotes modularity and reusability, it lays the foundation of structured
programming in C.
Let us take an example to illustrate the function without arguments and with return value in C.
Example
1. #include <stdio.h>
2.
4. return a * b;
5. }
6.
7. int main() {
10. return 0;
11. }
Output:
Product: 30
Explanation:
In this example, the product of two integers is calculated by the computer with the help of the user-
defined function multiply(). After that, two integers are taken as parameters, and their product is
returned by this function. In the main() function, the function is called with 5 and 6 as arguments and
the output is stored in result.
Advantage of functions in C
o Functions do away with code duplication. We write the logic once and use it wherever
needed.
o Code becomes simpler and more modular due to the ability of calling a function multiple
times from various parts of a program.
o It becomes much easier to manage, test, and understand when a large software application
is broken into smaller pieces.
o A major benefit of this is the ability to reuse code and employ the same function in multiple
systems without rebuilding it each time.
o Remember that there are costs involved in calling a function, i.e., supplying parameters and
making a jump to the memory address of the function. It can have a slight effect on
performance where quick response applications are concerned.
Disadvantages of functions in C
o Function call overhead is the extra time and memory needed for argument transmission and
control transfer.
o Data encapsulation is not present. Data cannot be concealed like OOP does; global variables
could lead to issues.
o Code that is hard to read can be caused by the use of too many tiny functions.
o Due to the difficulty of tracking errors across multiple procedures, debugging becomes more
challenging.
o The same function name cannot be used with different arguments because there is no
function overloading.
o Since there are no built-in parameters, all of them must be specified individually.
o Tight coupling means modifying one function that could affect other functions in large
programs.
Conclusion
In conclusion, functions are essential to C programming because they give program organization,
reusability, and modularity. Developers can avoid repeatedly creating the same code by breaking up
huge programs into smaller functions, which makes the code more effective and simpler to maintain.
We can call a function anywhere in the program, which provides flexibility and improves the control
flow.
Overall, functions are crucial building blocks in C programming, which provides benefits including
increased organization, code reuse, and simple tracking of huge programs. Function calls could add
some overhead, but their advantages outweigh the minimal performance hit. Programmers may
write effective and modular C programs by comprehending and using functions.
C Functions FAQ's
A return type is necessary for all C functions. The return type should be clearly indicated as void if it
returns nothing.
A declaration provides the compiler with the name, parameters, prototype, and return type of a
function, while a definition includes its logic or implementation.
Yes, one function in C can call another. It is common in structured programming and facilitates the
distribution of work over numerous reusable components.
1. #include <stdio.h>
2. void getarray(int arr[])
3. {
4. int i;
5. printf("Elements of array are : ");
6. for(i=0;i<5;i++)
7. printf("%d ", arr[i]);
8. }
9. int main()
10.{
11. int arr[5]={45,67,34,78,90};
12. getarray(arr);
13. return 0;
14.}
In the above program, we have first created the array arr[] and then we pass this array to the
function getarray(). The getarray() function prints all the elements of the array arr[].
Output
Another Example:
#include <stdio.h>
void arr(int []);
void main()
{
int a[5]={1,2,3,4,5};
arr(a);
}
void arr(int a[5])
{
int i;
for(i=0;i<5;i++)
printf("%d",a[i]);
}
1. #include <stdio.h>
3. {
5. for(int i=0;i<5;i++)
6. {
8. }
9. }
11. {
13. printarray(arr);
14. return 0;
15. }
In the above code, we have passed the array to the function as a pointer. The
function printarray() prints the elements of an array.
Output
Note: From the above examples, we observe that array is passed to a function as a reference which
means that array also persist outside the function.
1. #include <stdio.h>
2. int *getarray()
3. {
4. int arr[5];
6. for(int i=0;i<5;i++)
7. {
8. scanf("%d", &arr[i]);
9. }
11. }
13. {
15. n=getarray();
18. {
20. }
21. return 0;
22. }
In the above program, getarray() function returns a variable 'arr'. It returns a local variable, but it is
an illegal memory location to be returned, which is allocated within a function in the stack. Since the
program control comes back to the main() function, and all the variables in a stack are freed.
Therefore, we can say that this program is returning memory location, which is already de-allocated,
so the output of the program is a segmentation fault.
Output
o Using structure
1. #include <stdio.h>
3. {
4.
6. for(int i=0;i<5;i++)
7. {
8. scanf("%d", &a[i]);
9. }
10. return a;
11. }
13. {
16. n=getarray(a);
19. {
21. }
22. return 0;
23. }
Output
1. #include <stdio.h>
2. #include<malloc.h>
3. int *getarray()
4. {
5. int size;
7. scanf("%d",&size);
11. {
12. scanf("%d",&p[i]);
13. }
14. return p;
15. }
17. {
19. ptr=getarray();
23. {
25. }
26. return 0;
27. }
Output
Using Static Variable
1. #include <stdio.h>
2. int *getarray()
3. {
6. for(int i=0;i<7;i++)
7. {
8. scanf("%d",&arr[i]);
9. }
11.
12. }
14. {
16. ptr=getarray();
19. {
21. }
22. }
In the above code, we have created the variable arr[] as static in getarray() function, which is
available throughout the program. Therefore, the function getarray() returns the actual memory
location of the variable 'arr'.
Output
Using Structure
The structure is a user-defined data type that can contain a collection of items of different types.
Now, we will create a program that returns an array by using structure.
1. #include <stdio.h>
2. #include<malloc.h>
3. struct array
4. {
5. int arr[8];
6. };
8. {
9. struct array y;
12. {
13. scanf("%d",&[Link][i]);
14. }
15. return y;
16. }
18. {
24. }
25. return 0;
26. }
Output