You are on page 1of 54

CSIR11-INTRODUCTION TO

COMPUTER PROGRAMMING
UNIT III
(Functions (cont.),Arrays- Defining an array- Processing an array- Multi dimensional arrays)

DATE: 09/10/2023
Functions
• Syntax of Functions in C
1. Function Declaration
2. Function Definition
3. Function Calls
• Function Declaration:
• The function name, its return type, and the number and type of its parameters. A function
declaration tells the compiler that there is a function with the given name defined somewhere
else in the program.
• return_type name_of_the_function (parameter_1, parameter_2);
• The parameter name is not mandatory while declaring functions. We can also declare the
function without using the name of the data variables.
• Example:
• int sum(int a, int b);
• int sum(int , int);
Functions
Functions
• Function Definition
• The function definition consists of actual statements which are executed when
the function is called (i.e. when the program control comes to the function).
• A C function is generally defined and declared in a single step because the
function definition always starts with the function declaration so we do not
need to declare it explicitly. The below example serves as both a function
definition and a declaration.
return_type function_name (para1_type para1_name, para2_type para2_name)
{
// body of the function
}
Functions
Functions
• Function Call
• A function call is a statement that instructs the compiler to execute the
function. We use the function name and parameters in the function call.
• Note: Function call is neccessary to bring the program control to the function
definition. If not called, the function statements will not be executed.
Functions
Functions
• Function Return Type
• Function return type tells what type of value is returned after all function is
executed. When we don’t want to return a value, we can use the void data
type.
• int func(parameter_1,parameter_2);
• Note: Only one value can be returned from a C function. To return multiple
values, we have to use pointers or structures.
Functions
• Function Arguments
• Function Arguments (also known as Function Parameters) are the data that is
passed to a function.
• int function_name(int var1, int var2);
• Conditions of Return Types and Arguments
1.Function with no arguments and no return value
2.Function with no arguments and with return value
3.Function with argument and with no return value
4.Function with arguments and with return value
Functions
• Types of Functions
Functions
• Passing Parameters to Functions
Functions
• We can pass arguments to the C function in two ways:
1.Pass by Value
2.Pass by Reference
• Pass by Value
• Parameter passing in this method copies values from actual parameters into
formal function parameters. As a result, any changes made inside the functions
do not reflect in the caller’s parameters.
Functions
• Example:
// C program to show use of call by value
#include <stdio.h>
void swap(int var1, int var2)
{
int temp = var1;
var1 = var2;
var2 = temp;
} Output
Before swap Value of var1 and var2 is: 3, 2
After swap Value of var1 and var2 is: 3, 2
// Driver code
int main()
{
int var1 = 3, var2 = 2;
printf("Before swap Value of var1 and var2 is: %d, %d\n",var1, var2);
swap(var1, var2);
printf("After swap Value of var1 and var2 is: %d, %d",var1, var2);
return 0;
}
Functions
• Pass by Reference
• The caller’s actual parameters and the function’s actual parameters
refer to the same locations, so any changes made inside the function
are reflected in the caller’s actual parameters.
Functions
• Example:
// C program to show use of call by Reference
#include <stdio.h>
void swap(int *var1, int *var2)
{
int temp = *var1;
*var1 = *var2;
*var2 = temp;
} Output
Before swap Value of var1 and var2 is: 3, 2
After swap Value of var1 and var2 is: 2, 3
// Driver code
int main()
{
int var1 = 3, var2 = 2;
printf("Before swap Value of var1 and var2 is: %d, %d\n",var1, var2);
swap(&var1, &var2);
printf("After swap Value of var1 and var2 is: %d, %d",var1, var2);
return 0;
}
• main Function in C
• The main function in C is the entry point of a program where the
execution of a program starts.
• Types of C main Functions
1.Main function with no arguments and void return type
2.Main function with no arguments and int return type
3.Main function with the Command Line Arguments
Functions
• Main function with no arguments and void return type
// C Program to show main with no return type and no arguments
#include <stdio.h>
// Defining a main function
void main()
{

// code
printf("Hello!");
}
Functions
• Main Function with No Arguments and int Return Type
• The int return type in the main() function that indicates the exit status of the program.
• The exit status is a way for the program to communicate to the operating system whether
the program was executed successfully or not.
• The convention is that a return value of 0 indicates that the program was completed
successfully, while any other value indicates that an error occurred.
// C Program to show the main function with int return type and no arguments
#include <stdio.h>
int main()
{
printf("Hello!");
return 0;
}
Functions
• Main Function with the Command Line Arguments
• Command line arguments are given at the time of executing a program.
• The first argument argc means argument count which means it stores the
number of arguments passed in the command line and by default, its value is
1 when no argument is passed.
• The second argument is a char pointer array argv[] which stores all the
command line arguments passed.
• When we run the program without passing any command line argument the
value of argc is 1.
Functions
Functions
• Implicit return type int in C
• In C, if we do not specify a return type, compiler assumes an implicit return type as int.
However, C99 standard doesn’t allow return type to be omitted even if return type is int.
This was allowed in older C standard C89.
#include <stdio.h>
fun(int x)
{
return x*x;
}
int main(void)
{
printf("%d", fun(10));
return 0;
}
Arrays
• C Arrays
• One of the most used data structures in C programming. It is a simple and fast
way of storing multiple values under a single name.
• An array in C is a fixed-size collection of similar data items stored in
contiguous memory locations.
• It can be used to store the collection of primitive data types such as int, char,
float, etc., and also derived and user-defined data types such as pointers,
structures, etc.
Arrays
Arrays
• C Array Declaration
• We can declare an array by specifying its name, the type of its elements, and
the size of its dimensions.
• When we declare an array in C, the compiler allocates the memory block of
the specified size to the array name.
• Syntax
data_type array_name [size];
or
data_type array_name [size1] [size2]...[sizeN];
where N is the number of dimensions.
Arrays
Arrays
• The C arrays are static in nature, i.e., they are allocated memory at the compile time.
// C Program to illustrate the array declaration
#include <stdio.h>
int main()
{
// declaring array of integers
int arr_int[5];
// declaring array of characters
char arr_char[5];

return 0;
}
Arrays
• C Array Initialization
• When the array is declared or allocated memory, the elements of the array
contain some garbage value. So, we need to initialize the array to some
meaningful value.
1. Array Initialization with Declaration
• We use an initializer list to initialize multiple elements of the array. An
initializer list is the list of values enclosed within braces { } separated b a
comma.
• data_type array_name [size] = {value1, value2, ... valueN};
Arrays
Arrays
2. Array Initialization with Declaration without Size
• If we initialize an array using an initializer list, we can skip declaring the size
of the array as the compiler can automatically deduce the size of the array in
these cases.
• The size of the array in these cases is equal to the number of elements present
in the initializer list as the compiler can automatically deduce the size of the
array.
• data_type array_name[ ] = {1,2,3,4,5};
• The size of the above array is 5 which is automatically deduced by the
compiler.
Arrays
• 3. Array Initialization after Declaration (Using Loops)
• We initialize the array after the declaration by assigning the initial value to
each element individually. We can use for loop, while loop, or do-while loop
to assign the value to each element of the array.
• Example:
for (int i = 0; i < N; i++) {
array_name[i] = valuei;
}
Arrays
// C Program to demonstrate array initialization
#include <stdio.h>
int main()
{
// array initialization using initialier list
int arr[5] = { 10, 20, 30, 40, 50 };

// array initialization using initializer list without


// specifying size
int arr1[] = { 1, 2, 3, 4, 5 };

// array initialization using for loop


float arr2[5];
for (int i = 0; i < 5; i++)
{
arr2[i] = (float)i * 2.1;
}
return 0;
}
Arrays
• Access Array Elements
• We can access any element of an array in C using the array subscript operator
[ ] and the index value i of the element.
• array_name [index];
• One thing to note is that the indexing in the array always starts with 0, i.e.,
the first element is at index 0 and the last element is at N – 1 where N is the
number of elements in the array.
Arrays
Arrays
// C Program to illustrate element access using array subscript
#include <stdio.h>
int main()
{
// array declaration and initialization
int arr[5] = { 15, 25, 35, 45, 55 };
Output:
Element at arr[2]: 35
// accessing element at index 2 i.e 3rd element Element at arr[4]: 55
printf("Element at arr[2]: %d\n", arr[2]); Element at arr[0]: 15

// accessing element at index 4 i.e last element


printf("Element at arr[4]: %d\n", arr[4]);

// accessing element at index 0 i.e first element


printf("Element at arr[0]: %d", arr[0]);
return 0;
}
Arrays
• Update Array Element
• We can update the value of an element at the given index i in a similar way to
accessing an element by using the array subscript operator [ ] and assignment
operator =.
• array_name[i] = new_value;
Arrays
• C Array Traversal
• Traversal is the process in which we visit every element of the data structure.
• For C array traversal, we use loops to iterate through each element of the
array.
Arrays
// C Program to demonstrate the use of array
#include <stdio.h>
int main()
{
// array declaration and initialization
int arr[5] = { 10, 20, 30, 40, 50 };

// modifying element at index 2


arr[2] = 100;

// traversing array using for loop


printf("Elements in Array: "); Output:
Elements in Array: 10 20 100 40 50
for (int i = 0; i < 5; i++)
{
printf("%d ", arr[i]);
}
return 0;
}
Arrays
• Types of Array in C
• One Dimensional Arrays (1D Array)
• Multidimensional Arrays
1. One Dimensional Array in C
• Have only one dimension.
• array_name [size];
• Array of Characters (Strings)
• In C, we store the words, i.e., a sequence of characters in the form of an array
of characters terminated by a NULL character. These are called strings in C
language.
Arrays
// C Program to illustrate strings
#include <stdio.h>
int main()
{
// creating array of character
char arr[6] = { ‘H', 'e’, ‘l', ‘l', ‘o', '\0' };

// printing string
int i = 0;
while (arr[i]) {
printf("%c", arr[i++]);
}
return 0;
}
Arrays
2. Multidimensional Array in C
• Have more than one dimension.
• Some of the popular multidimensional arrays are 2D arrays and 3D arrays.
• We can declare arrays with more dimensions than 3d arrays but they are
avoided as they get very complex and occupy a large amount of space.
A. Two-Dimensional Array in C
• Has exactly two dimensions. They can be visualized in the form of rows and
columns organized in a two-dimensional plane.
• array_name[size1] [size2];
Arrays
Arrays
// C Program to illustrate 2d array
#include <stdio.h>
int main()
{
// declaring and initializing 2d array
int arr[2][3] = { 10, 20, 30, 40, 50, 60 };

printf("2D Array:\n");
// printing 2d array
Output:
for (int i = 0; i < 2; i++) {
2D Array:
for (int j = 0; j < 3; j++) {
printf("%d ",arr[i][j]); 10 20 30
} 40 50 60
printf("\n");
}

return 0;
}
Arrays
B. Three-Dimensional Array in C
• Has exactly three dimensions.
• It can be visualized as a collection of 2D arrays stacked on top of each other to
create the third dimension.
• array_name [size1] [size2] [size3];
Arrays
Arrays
// C Program to illustrate the 3d array
#include <stdio.h>
int main()
{
// 3D array declaration
int arr[2][2][2] = { 10, 20, 30, 40, 50, 60 };
// printing elements
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) { Output
for (int k = 0; k < 2; k++) { 10 20
printf("%d ", arr[i][j][k]); 30 40
}
printf("\n");
}
50 60
printf("\n \n");
}
00
return 0;
}
Arrays
• Relationship between Arrays and Pointers
• Arrays and Pointers are closely related to each other such that we can use
pointers to perform all the possible operations of the array.
• The array name is a constant pointer to the first element of the array and the
array decays to the pointers when passed to the function.
Arrays
// C Program to demonstrate the relation between arrays and
// pointers
#include <stdio.h>
int main()
{
int arr[5] = { 10, 20, 30, 40, 50 };
int* ptr = &arr[0];

// comparing address of first element and address stored


// inside array name
printf("Address Stored in Array name: %p\n Address of 1st Array Element: %p\n",arr, &arr[0]);

// printing array elements using pointers


printf("Array elements using pointer: ");
for (int i = 0; i < 5; i++) {
printf("%d ", *ptr++); Output
} Address Stored in Array name: 0x7ffce72c2660
return 0; Address of 1st Array Element: 0x7ffce72c2660
}
Array elements using pointer: 10 20 30 40 50
Arrays
• Passing an Array to a Function in C
• An array is always passed as pointers to a function in C. Whenever we try to
pass an array to a function, it decays to the pointer and then passed as a
pointer to the first element of an array.
Arrays
// C Program to pass an array to a function
#include <stdio.h>
void printArray(int arr[])
{
printf("Size of Array in Functions: %d\n", sizeof(arr));
printf("Array Elements: ");
for (int i = 0; i < 5; i++) {
printf("%d ",arr[i]);
}
}
// driver code
int main()
{
int arr[5] = { 10, 20, 30, 40, 50 };
printf("Size of Array in main(): %d\n", sizeof(arr));
printArray(arr); Output
return 0;
Size of Array in main(): 20
}
Size of Array in Functions: 8
Array Elements: 10 20 30 40 50
Arrays
• In C, when you pass an array to a function, you are actually passing a
pointer to the first element of the array. Therefore, the sizeof(arr)
inside the printArray function will not give you the size of the array
but rather the size of the pointer, which is typically 4 or 8 bytes
depending on your system (4 bytes on a 32-bit system and 8 bytes on
a 64-bit system).
Arrays
• Return an Array from a Function in C
• In C, we can only return a single value from a function. To return multiple
values or elements, we have to use pointers. We can return an array from a
function using a pointer to the first element of that array.
Arrays
// C Program to return array from a function
#include <stdio.h>
// function
int* func()
{
static int arr[5] = { 1, 2, 3, 4, 5 };
return arr;
}
// driver code
int main()
{
int* ptr = func();
printf("Array Elements: "); Output
for (int i = 0; i < 5; i++) { Array Elements: 1 2 3 4 5
printf("%d ", *ptr++);
}
return 0;
}
Arrays
• Properties of Arrays in C
• Fixed Size
• Homogeneous Collection
• Indexing in Array
• Dimensions of an Array
• Contiguous Storage
• Random Access
• No Index Out of Bounds Checking: In C, it is not a compiler error to initialize
an array with more elements than the specified size.
Thank you

You might also like