0% found this document useful (0 votes)
8 views61 pages

C Operators

The document provides an overview of various types of C operators including arithmetic, relational, logical, bitwise, assignment, and conditional operators, along with examples for each type. It explains the role of operands in operations and illustrates how these operators function through code snippets. Additionally, it covers the precedence of operators and includes explanations of specific operators like increment, decrement, and the ternary operator.

Uploaded by

Sekhar Muthangi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views61 pages

C Operators

The document provides an overview of various types of C operators including arithmetic, relational, logical, bitwise, assignment, and conditional operators, along with examples for each type. It explains the role of operands in operations and illustrates how these operators function through code snippets. Additionally, it covers the precedence of operators and includes explanations of specific operators like increment, decrement, and the ternary operator.

Uploaded by

Sekhar Muthangi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Type of C Operators

C operators can be classified into the following types:

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?

 Every operator works with some values.

 The value with which an operator works is called as 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 C language supports all the basic arithmetic operators such


as addition, subtraction, multiplication, division, etc.

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)

+ adds two operands (values) a+b

- subtract second operands from first a-b

* multiply two operands a*b

divide the numerator by the denominator, i.e. divide the


/ operand on the left side with the operand on the right a/b
side
Example
Operato
Description (where a and b are variables with
r
some integer value)

This is the modulus operator, it returns the remainder of


% a%b
the division of two operands as the result

This is the Increment operator - increases the integer


++ a++ or ++a
value by one. This operator needs only a single operand.

This is the Decrement operator - decreases integer value


-- --b or b--
by one. This operator needs only a single operand.

To learn in what order the arithmetic operators are executed, visit C Operator Precedence.

Code Example: Basic Arithmetic Operators

Let's see a code example to understand the use of the basic arithmetic operators in C programs.

#include <stdio.h>

int main() {

int a = 50, b = 23, result;

// addition

result = a+b;

printf("Addition of a & b = %d \n",result);

// subtraction

result = a-b;

printf("Subtraction of a & b = %d \n",result);

// multiplication

result = a*b;

printf("Multiplication of a & b = %d \n",result);


// division

result = a/b;

printf("Division of a & b = %d \n",result);

return 0;

Addition of a & b = 73

Subtraction of a & b = 27

Multiplication of a & b = 1150

Division of a & b = 2

Code Example: Using Modulus Operator (%)

The modulus operator returns the remainder value after the division of the provided values.

#include <stdio.h>

int main() {

int a = 23, b = 20, result;

// Using Modulus operator

result = a%b;

printf("result = %d",result);

return 0;

result = 3

Code Example: Using Increment and Decrement Operators


 The increment operator is used to increase the value of any numeric value by 1.

 The decrement operator is used to decrease the value of any numeric value by 1.

#include <stdio.h>

int main() {

int a = 10, b = 20, c, d;

/*

Using increment operator

*/

printf("Incrementing value of a = %d \n", ++a);

/*

Using decrement operator

*/

printf("Decrementing value of b = %d \n", --b);

// first print value of a, then decrement a

printf("Decrementing value of a = %d \n", a--);

printf("Value of a = %d \n", a);

// first print value of b, then increment b

printf("Incrementing value of b = %d \n", b++);

printf("Value of b = %d \n", b);

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.

 It returns 1 if the relationship checks pass, otherwise, it returns 0.

 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 if the two operands are equal a == b, returns 0

a != b, returns 1 because a is not


!= Check if the two operands are not equal.
equal to b

Check if the operand on the left is greater than the operand


> a > b, returns 0
on the right

< 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

Check if the operand on the left is smaller than or equal to


<= a <= b, returns 1
the right operand

To learn in what order the relational operators are executed, visit C Operator Precedence.

Code Example: Relational Operators

 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.

We will see the same in the example below.

#include <stdio.h>

int main() {

int a = 10, b = 20, result;

// Equal

result = (a==b);

printf("(a == b) = %d \n",result);

// less than

result = (a<b);

printf("(a < b) = %d \n",result);

// greater than

result = (a>b);

printf("(a > b) = %d \n",result);

// less than equal to

result = (a<=b);

printf("(a <= b) = %d \n",result);

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

C language supports the following 3 logical operators.

Example
Operator Description
(a and b, where a = 1 and b = 0)

&& Logical AND a && b, returns 0

|| Logical OR a || b, returns 1

! Logical NOT !a, returns 0

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.

3. The NOT operator changes true to false, and false to true.

Code Example: Logical Operators

In the code example below, we have used the logical operators.

#include <stdio.h>

int main() {

int a = 1, b = 0, result;

// And

result = (a && b);

printf("a && b = %d \n",result);

// 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

 Bitwise operators perform manipulations of data at the bit level.

 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).

 There are 6 bitwise operators in C programming.

The following table contains the bitwise operators.

Operator Description

& Bitwise AND

| Bitwise OR

^ Bitwise Exclusive OR (XOR)

~ One's complement (NOT)

>> Shift right

<< Shift left

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.

a b a&b a|b a^b

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.

Bitwise >> and << operators

 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.

 Both operands have the same precedence.

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.

Bitwise One's Complement (~) Operator

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.

Code Example: Bitwise Left & Right shift Operators

Let's see an example to understand the bitwise operators in C programs.

#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

 The assignment operators are used to assign value to a variable.

 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)

assigns values from right side operand to left side


= a=b, a gets value 5
operand

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.

Code Example: Using Assignment 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

6. Ternary Operator (?) in C

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 basic syntax for using ternary operator is:

(Expression1)? Expression2 : Expression3;

Here is how it works:

 The question mark ? in the syntax represents the if part.

 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 true then the (expression 2) is executed.

 If (expression 1) returns false then the expression on the right side of : i.e (expression 3) is
executed.

Code Example: Using Ternary Operator

Here is a code example to show how to use the ternary operator.

#include <stdio.h>

int main() {

int a = 20, b = 20, result;

/* Using ternary operator

- If a == b then store a+b in result

- otherwise store a-b in result

*/

result = (a==b)?(a+b):(a-b);

printf("result = %d",result);

return 0;

result = 40

7. C Special Operator - &, *, sizeof, etc.

Apart from arithmetic, relational, logical, assignment, etc. operators, C language uses some other
operators such as:

1. sizeof operator
2. & operator

3. * operator

4. The . (dot) and -> (arrow) operators

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.

Operator Description Example

returns the size(length in bytes) of


sizeof the entity, for eg. a variable or an sizeof(x) will return the size of the variable x
array, etc.

returns the memory address of the


& &x will return the address of the variable x
variable

represents a pointer to an object. m = &x (memory address of the variable x)


* The * operator returns the value *m will return the value stored at the memory
stored at a memory address. address m

. (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.

used to access structure or union


-> (arrow) If p is a pointer to the emp structure, then we can
elements using a pointer to the
operator access age element using p->age
structure or union.

if arr is an array, then we can access its values


used to access array elements using
[] operator using arr[index], where index represents the array
indexing
index starting from zero

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.

Code Example: Using 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

printf("Size of a is: %d \n", sizeof(a));

printf("Size of b is: %d \n", sizeof(b));

printf("Size of c is: %d \n", sizeof(c));

// & operator

printf("Memory address of a: %d \n", &a);

return 0;

OUTPUT:

Size of a is: 4

Size of b is: 1

Size of c is: 8

Memory address of a: 1684270284

C Control Flow Examples

Check whether a number is even or odd

Check whether a character is a vowel or consonant

Find the largest number among three numbers

Check Whether the Entered Year is Leap Year or not

Check Whether a Number is Positive or Negative or Zero.

Checker whether a character is an alphabet or not

Find the sum of natural numbers

Find factorial of a number


Generate multiplication table

Display Fibonacci series

Find HCF of two numbers

Find LCM of two numbers

Count number of digits of an integer

Reverse a number

Calculate the power of a number

Check whether a number is a palindrome or not

Check whether an integer is prime or Not

Display prime numbers between two intervals

Check Armstrong number

Display Armstrong numbers between two intervals

Display factors of a number

Print pyramids and triangles

Create a simple calculator

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

It has the following syntax:

1. for (initialization; condition; increment/decrement)

2. {

3. // Statements to repeat(loop body)

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.

Flowchart of for Loop


As we can see in the flowchart, use the following steps to implement the for loop in C++:

Step 1: First, go to the for loop and initialize the variables and their values.

Step 2: Next, the control flow jumps to the condition statement.

Step 3: Here, the condition is tested:

o If the condition is true, it executes the loop body.

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.

C++ Example to Display Numbers from 1 to 5

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>

2. int main() //main function


3. {

4. for (int count = 1; count <= 5; count++)

5. {

6. printf("The number is: %d\n", count);

7. }

8. return 0;

9. }

Output:

The number is: 1

The number is: 2

The number is: 3

The number is: 4

The number is: 5

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.

C Example to Print Even Numbers Between 2 and 10

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>

2. int main() //main function

3. {

4. for (int num = 2; num<= 10; num += 2)

5. {

6. printf("The even number is: %d\n", num);

7. }

8. return 0;

9. }

Output:

The even number is: 2


The even number is: 4

The even number is: 6

The even number is: 8

The even number is: 10

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.

Nested for Loop in C

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

It has the following syntax:

1. for (initialization; condition; increment) {

2. for (initialization; condition; increment) {

3. // statement of inner loop

4. }

5. //statement of outer loop

6. }

Flowchart of the Nested for Loop in C


How do we use a nested for loop in C?

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.

o Structure the output by using line breaks or formatting methods as required.

C Nested for Loop Example

Let us take a simple example to illustrate the Nested for loop in C language.

Example

1. #include <stdio.h>

2. int main() //main function

3. {

4. int rows = 7;

5. for (int row_num = 1; row_num <= rows; row_num++)

6. {
7. for (int col_num = 1; col_num <= row_num; col_num++)

8. {

9. printf("%d ", col_num);

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.

C Example to print Star Pattern for Right-Angled Triangle

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>

2. int main() //main function

3. {

4. for (int row_no = 1; row_no <= 5; row_no++)

5. {

6. for (int column_no = 1; column_no <= row_no; column_no ++)

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.

 break is used with for, while, do-while and switch statement.

 When break is used in nested loops then, only the innermost loop is terminated.

The syntax for break statement is as follows −

Example

Following is the C program for break statement −


#include<stdio.h>

Void main( ) {

int i;
for (i=1; i<=5; i++)
{
printf ("%d", i);
if (i==3)
break;
}
}

Output

When the above program is executed, it produces the following 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;

for (i=1; i<=5; i++){

if (i==2)

continue;

printf("%d", i);

Output

When the above program is executed, it produces the following output −

1 345
Return :

It terminates the execution of function and returns the control of calling function

The syntax for return statement is as follows −

return[expression/value];

Example

Following is the C program for the return statement −

#include<stdio.h>

int value();

void main()

int a;

a=value();

printf("value function returned value %d",a);

int value()

int b=5;

return b;

Output

When the above program is executed, it produces the following output −

value function returned value 5

goto :

It is used after the normal sequence of program execution by transferring the control to some other
part of program.

The syntax for the goto statement is as follows −


Example

Following is the C program for the goto statement −

#include<stdio.h>

Void main( )

printf("Hello");

goto aditya;

printf("How are you");

aditya: printf("welcome");

Output

When the above program is executed, it produces the following 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.

In C programming, array is beneficial if we want to store


similar elements. For example, if we want to store the marks
of a student in 6 subjects, we don't need to define different
variables for the marks in the different subjects. Instead of
that, we can define an array that can store the marks in each
subject at the contiguous memory locations.
By using the array, we can access the elements easily. Only a
few lines of code are required to access the elements of the
array.
Properties of an Array
The array contains the following properties:
o Each element of an array is of the same data type and
carries the same size, i.e., int = 4 bytes.
o Elements of the array are stored at contiguous memory
locations where the first element is stored at the
smallest memory location.
o Elements of the array can be randomly accessed
because we can calculate the address of each element of
the array with the given base address and the size of the
data element.
Declaration of C Array
We can declare an array in the C language in the following
way.
1. data_type array_name[array_size];
Now, let us see the example to declare the array.
1. int marks[5];
Here, int is the data_type, marks are the array_name, and 5 is
the array_size.
Initialization of C Array
The simplest way to initialize an array is by using the index of
each element. We can initialize each element of the array by
using the index. Consider the following example.
1. marks[0]=80;//initialization of array
2. marks[1]=60;
3. marks[2]=70;
4. marks[3]=85;
5. marks[4]=75;
C Array Example
Let us take an example to illustrate an Array in C.

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.

Definition and Declaration of Function in C

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.

Syntax of Function Declaration

It has the following syntax:

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.

o function_name: It is used to represent the name of the function.

o parameter_list: It is used to represent the name of the parameter.

Function Declaration Example

Let us take an example to illustrate the function declaration in C.

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.

1. int addition(int a, int b)

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

It has the following syntax:

1. function_name(actual_arguments);

Function Call Example in C

Let us take an example to illustrate how a function calls in C.

1. int result = add(5, 10); // Calling the function and storing result

Simple Function Example in C

Let us take an example to illustrate function in C.

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.

3 string.h It contains all


string related
library functions
like gets(),
puts(),etc.

4 stdlib.h This header file


contains all the
general library
functions like
malloc(), calloc(),
exit(), etc.

5 math.h This header file


contains all the
math operations
related functions
like sqrt(), pow(),
etc.

6 time.h This header file


contains all the
time-related
functions.

7 ctype.h This header file


contains all
character
handling
functions.

8 stdarg.h Variable
argument
functions are
defined in this
header file.
15. result = multiply(4, 5);

16.

17. printf("The Multiplication of Numbers is: %d\n", result);

18. return 0;

19. }

20.

21. // Function Definition

22. int multiply(int a, int b) {

23. return a * b;

24. }

Output:

The Multiplication of Numbers is: 20

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.

Return type of functions in C

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.

Key Features of Library Functions

Several key features of the library functions in C programming are as follows:


o The C Standard Library's library functions are more effective because they are already written
and compiled. It helps to ensure their independence from any platform, extensive testing,
and optimal performance.

o Pre-compiled solutions for fundamental operations, such as algebra, input/output


formatting, and even string manipulation offer immense value to programmers by saving
time and effort.

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 Examples of input/output functions are scanf() and printf().

o Use the strlen() and strcpy() function to handle strings.

o In mathematics, the functions ceil() and floor() are used to round integers.

Simple Library Function using Sqrt() function in C

Let us take an example to illustrate the library function in C using the sqrt() function.

Example

1. #include <stdio.h>

2. #include <math.h> // Required for sqrt()

3. int main() { //main function

4. double num = 169.0;

5. double result;

6.

7. // Using the sqrt() library function

8. result = sqrt(num);

9.

10. printf("The square root of %.2f is %.2f\n", num, result);

11. return 0;

12. }

Output:

The square root of 169.00 is 13.00

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.

Key Features of User Defined Functions in C

Several key features of user-defined functions in C programming are as follows:

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 A function's usefulness and variety may be enhanced by enabling it to accept parameters


and return values.

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.

User Defined Functions Example in C

Let us take an example to illustrate the user-defined function in C.

Example

1. #include <stdio.h>

2. // User-defined function declaration

3. void temp();

4. int main() {

5. // Function call

6. tpoint();

7. return 0;

8. }

9. // User-defined function definition

10. void temp() {

11. printf("Hello! Welcome to the Tech.\n");

12. }

Output:

Hello! Welcome to the Tech.


Explanation:

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.

Key differences between library functions and User Defined functions

Several differences between library functions and user defined functions in C are as follows:

Features Library Functions User-Defined Functions

Control over Logic No, it is predefined Yes, it is created by the programmer.


function.

Flexibility Limited High, it is customized for specific use cases.

Compilation Already compiled It is compiled along with the main program.

Debugging Generally not needed It is required when logic is complex.

Reusability High but generic High and tailored

Types of User Defined Function in C

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.

o function without arguments and without return value

o function without arguments and with return value

o function with arguments and without return value

o function with arguments and with return value

Now, we will discuss these user-defined functions one by one in C.

Function without arguments and without return value

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.

Function without arguments and without return value Example

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.

Function without arguments and with return value

In C programming, this approach does not take any arguments. It also returns a value to the caller.

Function without arguments and with return value Example

Let us take an example to illustrate the function without arguments and without return value in C.

Example

1. #include <stdio.h>

2.

3. int getNumber() { // No arguments, but returns an int

4. return 100;

5. }

6.

7. int main() {

8. int num = getNumber(); // Function call

9. printf("Returned number is: %d\n", num);


10. return 0;

11. }

Output:

Returned number is: 100

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.

Function with arguments and without return value

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.

Function with arguments and without return value Example

Let us take an example to illustrate the Function with arguments and without return value in C.

Example

1. #include<stdio.h>

2. void sum(int, int);

3. void main()

4. {

5. int a,b,result;

6. printf("\nGoing to calculate the sum of two numbers:");

7. printf("\nEnter two numbers:");

8. scanf("%d %d",&a,&b);

9. sum(a,b);

10. }

11. void sum(int a, int b)

12. {

13. printf("\nThe sum is %d",a+b);

14. }

Output:

Going to calculate the sum of two numbers:

Enter two numbers:12 34

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.

Function without arguments and with return value

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.

Function without arguments and with return value Example

Let us take an example to illustrate the function without arguments and with return value in C.

Example

1. #include <stdio.h>

2.

3. int multiply(int a, int b) { // Takes arguments and returns a value

4. return a * b;

5. }

6.

7. int main() {

8. int result = multiply(5, 6); // Function call

9. printf("Product: %d\n", result);

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

Several advantages of functions in C are as follows:

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

Several disadvantages of functions in C are as follows:

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

1) What are the several ways to call functions in C?

There are several ways to call functions in C. These are as follows:

o Without arguments and without return value


o Without arguments and with return value

o With arguments and without return value

o With arguments and with return value

2) Why do C programmers utilize functions?

In C programming, functions enhance modularity, eliminate redundancy, and improve the


understanding of programs, debugging and maintenance. They also facilitate reuse in different
portions of a program or across many projects.

3) Could a C function have no return type at all?

A return type is necessary for all C functions. The return type should be clearly indicated as void if it
returns nothing.

4) What is the difference between function declaration and definition?

A declaration provides the compiler with the name, parameters, prototype, and return type of a
function, while a definition includes its logic or implementation.

5) Is it possible for one function in C to call another?

Yes, one function in C can call another. It is common in structured programming and facilitates the
distribution of work over numerous reusable components.

how to pass a single-dimensional array to a function.


Passing array to a function

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]);
}

Passing array to a function as a pointer

Now, we will see how to pass an array to a function as a pointer.

1. #include <stdio.h>

2. void printarray(char *arr)

3. {

4. printf("Elements of array are : ");

5. for(int i=0;i<5;i++)

6. {

7. printf("%c ", arr[i]);

8. }

9. }

10. int main()

11. {

12. char arr[5]={'A','B','C','D','E'};

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.

How to return an array from a function

Returning pointer pointing to the array

1. #include <stdio.h>

2. int *getarray()

3. {

4. int arr[5];

5. printf("Enter the elements in an array : ");

6. for(int i=0;i<5;i++)

7. {

8. scanf("%d", &arr[i]);

9. }

10. return arr;

11. }

12. int main()

13. {

14. int *n;

15. n=getarray();

16. printf("\nElements of array are :");

17. for(int i=0;i<5;i++)

18. {

19. printf("%d", n[i]);

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

There are three right ways of returning an array to a function:

o Using dynamically allocated array

o Using static array

o Using structure

Returning array by passing an array which is to be returned as a parameter to the function.

1. #include <stdio.h>

2. int *getarray(int *a)

3. {
4.

5. printf("Enter the elements in an array : ");

6. for(int i=0;i<5;i++)

7. {

8. scanf("%d", &a[i]);

9. }

10. return a;

11. }

12. int main()

13. {

14. int *n;

15. int a[5];

16. n=getarray(a);

17. printf("\nElements of array are :");

18. for(int i=0;i<5;i++)

19. {

20. printf("%d", n[i]);

21. }

22. return 0;

23. }

Output

Returning array using malloc() function.

1. #include <stdio.h>
2. #include<malloc.h>

3. int *getarray()

4. {

5. int size;

6. printf("Enter the size of the array : ");

7. scanf("%d",&size);

8. int *p= malloc(sizeof(size));

9. printf("\nEnter the elements in an array");

10. for(int i=0;i<size;i++)

11. {

12. scanf("%d",&p[i]);

13. }

14. return p;

15. }

16. int main()

17. {

18. int *ptr;

19. ptr=getarray();

20. int length=sizeof(*ptr);

21. printf("Elements that you have entered are : ");

22. for(int i=0;ptr[i]!='\0';i++)

23. {

24. printf("%d ", ptr[i]);

25. }

26. return 0;

27. }

Output
Using Static Variable

1. #include <stdio.h>

2. int *getarray()

3. {

4. static int arr[7];

5. printf("Enter the elements in an array : ");

6. for(int i=0;i<7;i++)

7. {

8. scanf("%d",&arr[i]);

9. }

10. return arr;

11.

12. }

13. int main()

14. {

15. int *ptr;

16. ptr=getarray();

17. printf("\nElements that you have entered are :");

18. for(int i=0;i<7;i++)

19. {

20. printf("%d ", ptr[i]);

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. };

7. struct array getarray()

8. {

9. struct array y;

10. printf("Enter the elements in an array : ");

11. for(int i=0;i<8;i++)

12. {

13. scanf("%d",&[Link][i]);

14. }

15. return y;

16. }

17. int main()

18. {

19. struct array x=getarray();

20. printf("Elements that you have entered are :");

21. for(int i=0;[Link][i]!='\0';i++)


22. {

23. printf("%d ", [Link][i]);

24. }

25. return 0;

26. }

Output

You might also like