0% found this document useful (0 votes)
2 views

Functions Array and Strings 2nd Year Notes

The document explains how to call C functions using two methods: call by value and call by reference, detailing their differences and providing example programs for each. It also covers character arrays and strings in C, including initialization, input/output methods, and string handling functions. Additionally, it discusses structures and unions in C programming, highlighting their definitions, usage, and examples.

Uploaded by

aazmeerrashid0
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Functions Array and Strings 2nd Year Notes

The document explains how to call C functions using two methods: call by value and call by reference, detailing their differences and providing example programs for each. It also covers character arrays and strings in C, including initialization, input/output methods, and string handling functions. Additionally, it discusses structures and unions in C programming, highlighting their definitions, usage, and examples.

Uploaded by

aazmeerrashid0
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

UNIT-VII

NOTES For

FUNCTIONS
Program Output
HOW TO CALL C FUNCTIONS IN A PROGRAM?
There are two ways that a C function can be called from a program. They are,

1. Call by value
2. Call by reference
1. CALL BY VALUE:
 In call by value method, the value of the variable is passed to the function as parameter.
 The value of the actual parameter can not be modified by formal parameter.
 Different Memory is allocated for both actual and formal parameters. Because, value of actual
parameter is copied to formal parameter.
Note:

 Actual parameter – This is the argument which is used in function call.


 Formal parameter – This is the argument which is used in function definition
EXAMPLE PROGRAM FOR C FUNCTION (USING CALL BY VALUE):
 In this program, the values of the variables “m” and “n” are passed to the function “swap”.
 These values are copied to formal parameters “a” and “b” in swap function and used.
1 #include<stdio.h>
2 // function prototype, also called function declaration
3 void swap(int a, int b);
4
5 int main()
6 {
7 int m = 22, n = 44;
8 // calling swap function by value
9 printf(" values before swap m = %d \nand n = %d", m, n);
10 swap(m, n);
11 }
12
13 void swap(int a, int b)
14 {
15 int tmp;
16 tmp = a;
17 a = b;
18 b = tmp;
19 printf(" \nvalues after swap m = %d\n and n = %d", a, b);
20 }
COMPILE & RUN
OUTPUT:
values before swap m = 22
and n = 44
values after swap m = 44
and n = 22
2. CALL BY REFERENCE:
 In call by reference method, the address of the variable is passed to the function as parameter.
 The value of the actual parameter can be modified by formal parameter.
 Same memory is used for both actual and formal parameters since only address is used by both
parameters.
EXAMPLE PROGRAM FOR C FUNCTION (USING CALL BY REFERENCE):
 In this program, the address of the variables “m” and “n” are passed to the function “swap”.
 These values are not copied to formal parameters “a” and “b” in swap function.
 Because, they are just holding the address of those variables.
 This address is used to access and change the values of the variables.
1 #include<stdio.h>
2 // function prototype, also called function declaration
3 void swap(int *a, int *b);
4
5 int main()
6 {
7 int m = 22, n = 44;
8 // calling swap function by reference
9 printf("values before swap m = %d \n and n = %d",m,n);
10 swap(&m, &n);
11 }
12
13 void swap(int *a, int *b)
14 {
15 int tmp;
16 tmp = *a;
17 *a = *b;
18 *b = tmp;
19 printf("\n values after swap a = %d \nand b = %d", *a, *b);
20 }
COMPILE & RUN
OUTPUT:
values before swap m = 22
and n = 44
values after swap a = 44
and b = 22

Difference between Call by Value and Call by Reference


Functions can be invoked in two ways: Call by Value or Call by Reference. These two ways are generally differentiated by the type of
values passed to them as parameters.
The parameters passed to function are called actual parameters whereas the parameters received by function are called
formal parameters.
Call By Value: In this parameter passing method, values of actual parameters are copied to function’s formal parameters and the two
types of parameters are stored in different memory locations. So any changes made inside functions are not reflected in actual
parameters of caller.
Call by Reference: Both the actual and formal parameters refer to same locations, so any changes made inside the function are
actually reflected in actual parameters of caller.

CALL BY VALUE CALL BY REFERENCE

While calling a function, instead of passing the values of

While calling a function, we pass values of variables to it. variables, we pass address of variables(location of variables)

Such functions are known as “Call By Values”. to the function known as “Call By References.

In this method, the value of each variable in calling In this method, the address of actual variables in the

function is copied into corresponding dummy variables of calling function are copied into the dummy variables of the

the called function. called function.

With this method, the changes made to the dummy With this method, using addresses we would have an access

variables in the called function have no effect on the to the actual variables and hence we would be able to

values of actual variables in the calling function. manipulate them.

In call by values we cannot alter the values of actual In call by reference we can alter the values of variables

variables through function calls. through function calls.

Pointer variables are necessary to define to store the

Values of variables are passes by Simple technique. address values of variables.


UNIT-IV

NOTES For

ARRAYS
Array in C programming
CHARACTER ARRAY AND STRING IN C
String and Character Array
String is a sequence of characters that is treated as a single data item and terminated by null character '\0'.
Remember that C language does not support strings as a data type. A string is actually one-dimensional array
of characters in C language. These are often used to create meaningful and readable programs.
For example: The string "hello world" contains 12 characters including '\0' character which is automatically
added by the compiler at the end of the string.

Declaring and Initializing a string variables


There are different ways to initialize a character array variable.
char name[13] = "StudyTonight"; // valid character array initialization
char name[10] = {'L','e','s','s','o','n','s','\0'}; // valid initialization

Remember that when you initialize a character array by listing all of its characters separately then you must
supply the '\0' character explicitly.
Some examples of illegal initialization of character array are,
char ch[3] = "hell"; // Illegal

char str[4];
str = "hell"; // Illegal String Input and Output

Input function scanf() can be used with %s format specifier to read a string input from the terminal. But there is
one problem with scanf() function, it terminates its input on the first white space it encounters. Therefore if you
try to read an input string "Hello World" using scanf() function, it will only read Hello and terminate after
encountering white spaces.
However, C supports a format specification known as the edit set conversion code %[..] that can be used to
read a line containing a variety of characters, including white spaces.
#include<stdio.h>
#include<string.h>
void main()
{
char str[20];
printf("Enter a string");
scanf("%[^\n]", &str); //scanning the whole string, including the white spaces
printf("%s", str);
}
Another method to read character string with white spaces from terminal is by using the gets() function.
char text[20];
gets(text);
printf("%s", text);
String Handling Functions
C language supports a large number of string handling functions that can be used to carry out many of the
string manipulations. These functions are packaged in string.h library. Hence, you must include string.h
header file in your programs to use these functions.
The following are the most commonly used string handling functions.

Method Description

strcat() It is used to concatenate(combine) two strings

strlen() It is used to show length of a string

strrev() It is used to show reverse of a string

strcpy() Copies one string into another

strcmp() It is used to compare two string

strcat() function
strcat("hello", "world");
strcat() function will add the string "world" to "hello" i.e it will ouput helloworld.

strlen() function
strlen() function will return the length of the string passed to it.
int j;
j = strlen("studytonight");

printf("%d",j);

strcmp() function
strcmp() function will return the ASCII difference between first unmatching character of two strings.
int j;
j = strcmp("study", "tonight");

printf("%d",j);
strcpy() function
It copies the second string argument to the first string argument.
#include<stdio.h>
#include<string.h>

int main()
{
char s1[50];
char s2[50];

strcpy(s1, "StudyTonight"); //copies "studytonight" to string s1

strcpy(s2, s1); //copies string s1 to string s2

printf("%s\n", s2);

return(0);
}
strrev() function
It is used to reverse the given string expression.
#include<stdio.h>

int main()
{
char s1[50];
printf("Enter your string: ");
gets(s1);
printf("\nYour reverse string is: %s",strrev(s1));
return(0);
}

Enter your string: studytonight


Your reverse string is: thginotyduts
STRUCTURE IN C PROGRAMMING
Structure is a group of variables of different data types represented by a single name. Lets take an example to
understand the need of a structure in C programming.

Lets say we need to store the data of students like student name, age, address, id etc. One way of doing this
would be creating a different variable for each attribute, however when you need to store the data of multiple
students then in that case, you would need to create these several variables again for each student. This is
such a big headache to store data in this way.

We can solve this problem easily by using structure. We can create a structure that has members for name, id,
address and age and then we can create the variables of this structure for each student. This may sound
confusing, do not worry we will understand this with the help of example.

How to create a structure in C Programming


We use struct keyword to create a structure in C. The struct keyword is a short form of structured data
type.

struct struct_name {
DataType member1_name;
DataType member2_name;
DataType member3_name;

};
Here struct_name can be anything of your choice. Members data type can be same or different. Once we
have declared the structure we can use the struct name as a data type like int, float etc.

First we will see the syntax of creating struct variable, accessing struct members etc and then we will see a
complete example.

How to declare variable of a structure?

struct struct_name var_name;


or

struct struct_name {
DataType member1_name;
DataType member2_name;
DataType member3_name;

} var_name;
How to access data members of a structure using a struct variable?
var_name.member1_name;
var_name.member2_name;

How to assign values to structure members?
There are three ways to do this.
1) Using Dot(.) operator

var_name.memeber_name = value;
2) All members assigned in one statement
struct struct_name var_name =
{value for memeber1, value for memeber2 …so on for all the members}
3) Designated initializers – We will discuss this later at the end of this post.

Example of Structure in C

#include <stdio.h>
/* Created a structure here. The name of the structure is
* StudentData.
*/
struct StudentData{
char *stu_name;
int stu_id;
int stu_age;
};
int main()
{
/* student is the variable of structure StudentData*/
struct StudentData student;

/*Assigning the values of each struct member here*/


student.stu_name = "Steve";
student.stu_id = 1234;
student.stu_age = 30;

/* Displaying the values of struct members */


printf("Student Name is: %s", student.stu_name);
printf("\nStudent Id is: %d", student.stu_id);
printf("\nStudent Age is: %d", student.stu_age);
return 0;
}
Output:

Student Name is: Steve


Student Id is: 1234
Student Age is: 30

UNION IN C PROGRAMMING
C Union is also like structure, i.e. collection of different data types which are grouped together. Each element in
a union is called member.

 Union and structure in C are same in concepts, except allocating memory for their members.
 Structure allocates storage space for all its members separately.
 Whereas, Union allocates one common storage space for all its members
 We can access only one member of union at a time. We can’t access all member values at the same
time in union. But, structure can access all member values at the same time. This is because, Union
allocates one common storage space for all its members. Where as Structure allocates storage space
for all its members separately.
 Many union variables can be created in a program and memory will be allocated for each union
variable separately.
 Below table will help you how to form a C union, declare a union, initializing and accessing the
members of the union.
Using normal variable Using pointer variable
Syntax: Syntax:
union tag_name union tag_name
{ {
data type var_name1; data type var_name1;
data type var_name2; data type var_name2;
data type var_name3; data type var_name3;
}; };
Example: Example:
union student union student
{ {
int mark; int mark;
char name[10]; char name[10];
float average; float average;
}; };
Declaring union using Declaring union using
normal variable: pointer variable:
union student report; union student *report, rep;
Initializing union using
Initializing union using pointer variable:
normal variable: union student rep = {100,
union student report = {100, “Mani”, 99.5};
“Mani”, 99.5}; report = &rep;
Accessing union members Accessing union members
using normal variable: using pointer variable:
report.mark; report -> mark;
report.name; report -> name;
report.average; report -> average;
EXAMPLE PROGRAM FOR C UNION:
1 #include <stdio.h>
2 #include <string.h>
3
4 union student
5 {
6 char name[20];
7 char subject[20];
8 float percentage;
9 };
10
11 int main()
12 {
13 union student record1;
14 union student record2;
15
16 // assigning values to record1 union variable
17 strcpy(record1.name, "Raju");
18 strcpy(record1.subject, "Maths");
19 record1.percentage = 86.50;
20
21 printf("Union record1 values example\n");
22 printf(" Name : %s \n", record1.name);
23 printf(" Subject : %s \n", record1.subject);
24 printf(" Percentage : %f \n\n", record1.percentage);
25
26 // assigning values to record2 union variable
27 printf("Union record2 values example\n");
28 strcpy(record2.name, "Mani");
29 printf(" Name : %s \n", record2.name);
30
31 strcpy(record2.subject, "Physics");
32 printf(" Subject : %s \n", record2.subject);
33
34 record2.percentage = 99.50;
35 printf(" Percentage : %f \n", record2.percentage);
36 return 0;
37 }
OUTPUT:
Union record1 values example
Name :
Subject :
Percentage : 86.500000;
Union record2 values example
Name : Mani
Subject : Physics
Percentage : 99.500000
EXPLANATION FOR ABOVE C UNION PROGRAM:
There are 2 union variables declared in this program to understand the difference in accessing values of union
members.

Record1 union variable:


 “Raju” is assigned to union member “record1.name” . The memory location name is “record1.name”
and the value stored in this location is “Raju”.
 Then, “Maths” is assigned to union member “record1.subject”. Now, memory location name is changed
to “record1.subject” with the value “Maths” (Union can hold only one member at a time).
 Then, “86.50” is assigned to union member “record1.percentage”. Now, memory location name is
changed to “record1.percentage” with value “86.50”.
 Like this, name and value of union member is replaced every time on the common storage space.
 So, we can always access only one union member for which value is assigned at last. We can’t access
other member values.
 So, only “record1.percentage” value is displayed in output. “record1.name” and “record1.percentage”
are empty.
Record2 union variable:

 If we want to access all member values using union, we have to access the member before assigning
values to other members as shown in record2 union variable in this program.
 Each union members are accessed in record2 example immediately after assigning values to them.
 If we don’t access them before assigning values to other member, member name and value will be over
written by other member as all members are using same memory.
 We can’t access all members in union at same time but structure can do that.
EXAMPLE PROGRAM – ANOTHER WAY OF DECLARING C UNION:
In this program, union variable “record” is declared while declaring union itself as shown in the below program.

1 #include <stdio.h>
2 #include <string.h>
3
4 union student
5 {
6 char name[20];
7 char subject[20];
8 float percentage;
9 }record;
10
11 int main()
12 {
13
14 strcpy(record.name, "Raju");
15 strcpy(record.subject, "Maths");
16 record.percentage = 86.50;
17
18 printf(" Name : %s \n", record.name);
19 printf(" Subject : %s \n", record.subject);
20 printf(" Percentage : %f \n", record.percentage);
21 return 0;
22 }
OUTPUT:
Name :
Subject :
Percentage : 86.500000
NOTE:
 We can access only one member of union at a time. We can’t access all member values at the same
time in union.
 But, structure can access all member values at the same time. This is because, Union allocates one
common storage space for all its members. Where as Structure allocates storage space for all its
members separately.
DIFFERENCE BETWEEN STRUCTURE AND UNION IN C:
C Structure C Union
Union allocates one common storage
Structure allocates space for all its members.
storage space for all Union finds that which of its member
its members needs high storage space over other
separately. members and allocates that much
space
Structure occupies
higher memory Union occupies lower memory space
space. over structure.
We can access all
members of We can access only one member of
structure at a time. union at a time.
Structure example: Union example:
struct student union student
{ {
int mark; int mark;
char name[6]; char name[6];
double average; double average;
}; };
For above structure, For above union, only 8 bytes of
memory allocation memory will be allocated since
will be like below. double data type will occupy
int mark – 2B char maximum space of memory over
name[6] – 6B other data types.
double average – Total memory allocation=8 bytes
8B
Total memory
allocation = 2+6+8 =
16 Bytes

ENUMERATED DATA TYPE IN C


enum in C

Enumeration (enum) is a user-defined datatype (same as structure). It consists of various elements of that type. There is
no such specific use of enum, we use it just to make our codes neat and more readable. We can write C programs without
using enumerations also.
For example, Summer, Spring, Winter and Autumn are the names of four seasons. Thus, we can say that these are of
types season. Therefore, this becomes an enumeration with name season and Summer, Spring, Winter and Autumn as its
elements.
So, you are clear with the basic idea of enum. Now let's see how to define it.

Defining an Enum

An enum is defined in the same way as structure with the keyword struct replaced by the keyword enum and the elements
separated by 'comma' as follows.
enum enum_name
{
element1,
element2,
element3,
element4,
};

Now let's define an enum of the above example of seasons.


enum Season{
Summer,
Spring,
Winter,
Autumn
};

Here, we have defined an enum with name 'season' and 'Summer, Spring, Winter and Autumn' as its elements.

Declaration of Enum Variable

We also declare an enum variable in the same way as that of structures. We create an enum variable as follows.
enum season{
Summer,
Spring,
Winter,
Autumn
};
main()
{
enum season s;
}

So, here 's' is the variable of the enum named season. This variable will represent a season. We can also declare
an enum variable as follows.
enum season{
Summer,
Spring,
Winter,
Autumn
}s;

Values of the Members of Enum

All the elements of an enum have a value. By default, the value of the first element is 0, that of the second element is 1
and so on.

Let's see an example.

#include <stdio.h>
enum season{ Summer, Spring, Winter, Autumn};
int main()
{
enum season s;
s = Spring;
printf("%d\n",s);
return 0;
}

Output
Here, first we defined an enum named 'season' and declared its variable 's' in the main function as we have seen
before. The values of Summer, Spring, Winter and Autumn are 0, 1, 2 and 3 respectively. So, by writing s = Spring, we
assigned a value '1' to the variable 's' since the value of 'Spring' is 1.
We can also change the default value and assign any value of our choice to an element of enum. Once we change the
default value of any enum element, then the values of all the elements after it will also be changed accordingly. An
example will make this point clearer.

#include <stdio.h>
enum days{ sun, mon, tue = 5, wed, thurs, fri, sat};
int main()
{
enum days day;
day = thurs;
printf("%d\n",day);
return 0;
}

Output
The default value of 'sun' will be 0, 'mon' will be 1, 'tue' will be 2 and so on. In the above example, we defined the value
of tue as 5. So the values of 'wed', 'thurs', 'fri' and 'sat' will become 6, 7, 8 and 9 respectively. There will be no effect on
the values of sun and mon which will remain 0 and 1 respectively. Thus the value of thurs i.e. 7 will get printed.
Let's see one more example of enum.

#include <stdio.h>
enum days{ sun, mon, tue, wed, thurs, fri, sat};
int main()
{
enum days day;
day = thurs;
printf("%d\n",day+2);
return 0;
}

Output
In this example, the value of 'thurs' i.e. 4 is assigned to the variable day. Since we are printing 'day+2' i.e. 6 (=4+2), so the
output will be 6.

ARRAY OF STRUCTURE
Array of Structures in C
In C Programming, Structures are useful to group different data types to organize the data in a structural way. And
Arrays are used to group the same data type values. In this article, we will show you the Array of Structures in C
concept with one practical example.

For example, we are storing employee details such as name, id, age, address, and salary. We usually group
them as employee structure with the members mentioned above. We can create the structure variable to access
or modify the structure members. A company may have 10 to 100 employee, how about storing the same for 100
employees?

In C Programming, We can easily solve the problem mentioned above by combining two powerful concepts Arrays
of Structures in C. We can create the employee structure. Then instead of creating the structure variable, we
create the array of a structure variable.
Declaring C Array of Structures at structure Initialization
Let me declare an Array of Structures in C at the initialization of the structure

/* Array of Structures in C Initialization */


struct Employee
{
int age;
char name[50];
int salary;
} Employees[4] = {
{25, "Suresh", 25000},
{24, "Tutorial", 28000},
{22, "Gateway", 35000},
{27, "Mike", 20000}
};
Here, Employee structure is for storing the employee details such as age, name, and salary. We created the array of
structures variable Employees [4] (with size 4) at the declaration time only. We also initialized the values of each
structure member for all 4 employees.

From the above,

Employees[0] = {25, "Suresh", 25000}

Employees[1] = {24, "Tutorial", 28000}

Employees[2] = {22, "Gateway", 35000}

Employees[3] = {27, "Mike", 20000}


Declaring C Array of Structures in main() Function
/* Array of Structures in C Initialization */
struct Employee
{
int age;
char name[50];
int salary;
};
Within the main() function, Create the Employee Structure Variable

struct Employee Employees[4];


Employees[4] = {
{25, "Suresh", 25000},
{24, "Tutorial", 28000},
{22, "Gateway", 35000},
{27, "Mike", 20000}
};
Array of Structures in C Example
This program for an Array of Structures in C will declare the student structure and displays the information of
N number of students.

/* Array of Structures in C example */

#include <stdio.h>

struct Student
{
char Student_Name[50];
int C_Marks;
int DataBase_Marks;
int CPlus_Marks;
int English_Marks;
};

int main()
{
int i;
struct Student Students[4] =
{
{"Suresh", 80, 70, 60, 70},
{"Tutorial", 85, 82, 65, 68},
{"Gateway", 75, 70, 89, 82},
{"Mike", 70, 65, 69, 92}
};

printf(".....Student Details....");
for(i=0; i<4; i++)
{
printf("\n Student Name = %s", Students[i].Student_Name);
printf("\n First Year Marks = %d", Students[i].C_Marks);
printf("\n Second Year Marks = %d", Students[i].DataBase_Marks);
printf("\n First Year Marks = %d", Students[i].CPlus_Marks);
printf("\n Second Year Marks = %d", Students[i].English_Marks);
}

return 0;
}
OUTPUT:

ANALYSIS

Within this Array of Structures in C example, We declared the student structure with Student Name, C
Marks, DataBase Marks, C++ Marks, and English Marks members of different data types.

Within the main() function, we created the array of structures student variable. Next, we initialized the appropriate
values to the structure members
In the Next line, we have For Loop in C Programming Condition inside the for loop. It will control the compiler not to
exceed the array limit. The below printf statements will print the values inside the student structure array.

printf("\n Student Name = %s", Students[i].Student_Name);

printf("\n C Programming Marks = %d", Students[i].C_Marks);

printf("\n Data Base Marks = %d", Students[i].DataBase_Marks);

printf("\n C++ Marks = %d", Students[i].CPlus_Marks);

printf("\n English Marks = %d", Students[i].English_Marks);


Let us explore the Array of Structures in C program in iteration wise

First Iteration

Student Name = Students[i].Student_Name

C Programming Marks = Students[i].C_Marks

Data Base Marks = Students[i].DataBase_Marks

C++ Marks = Students[i].CPlus_Marks

English Marks = Students[i].English_Marks

i = 0 and the condition 0 < 4 is TRUE so

Student Name = Students[0].Student_Name = Suresh

C Programming Marks = Students[0].C_Marks = 80

Data Base Marks = Students[0].DataBase_Marks= 70

C++ Marks = Students[0].CPlus_Marks = 60

English Marks = Students[0].English_Marks = 70

i value incremented by 1 using i++ Incremental Operator. So i becomes 1

Second Iteration of Array of Structures in C

i = 1 and the condition 1 < 4 is TRUE

Student Name = Students[1].Student_Name = Tutorial

C Programming Marks = Students[1].C_Marks = 85

Data Base Marks = Students[1].DataBase_Marks = 82

C++ Marks = Students[1].CPlus_Marks = 65

English Marks = Students[1].English_Marks = 68


i value incremented by 1. So i becomes 2

Third Iteration

i = 2 and the condition 2 < 4 is TRUE

Student Name = Students[2].Student_Name = Gateway

C Programming Marks = Students[2].C_Marks = 75

Data Base Marks = Students[2].DataBase_Marks = 70

C++ Marks = Students[2].CPlus_Marks = 89

English Marks = Students[2].English_Marks = 82

i value incremented by 1. So i becomes 3

Fourth Iteration of the Array of Structures in C

i = 3, and the condition 3 < 4 is TRUE so,

Student Name = Students[0].Student_Name = Mike

C Programming Marks = Students[0].C_Marks = 70

Data Base Marks = Students[0].DataBase_Marks = 65

C++ Marks = Students[0].CPlus_Marks = 69

English Marks = Students[0].English_Marks = 92

i value incremented by 1 using i++ incremental Operator. So, i becomes 4, and the i<4 condition Fails. So,
the compiler will exit from the loop.
PASSING ARRAY TO FUNCTION IN c

How to pass Array to a Function in C


Whenever we need to pass a list of elements as argument to any function in C language, it is prefered to do so
using an array. But how can we pass an array as argument to a function? Let's see how its done.

Declaring Function with array as a parameter


There are two possible ways to do so, one by using call by value and other by using call by reference.

1. We can either have an array as a

parameter. int sum (int arr[]);

2. Or, we can have a pointer in the parameter list, to hold the base address of our array.

int sum (int* ptr);

We will study the second way in details later when we will study pointers.

Returning an Array from a function


We don't return an array from functions, rather we return a pointer holding the base address of the array to be returned.
But we must, make sure that the array exists after the function ends i.e. the array is not local to the function.
int* sum (int x[])

{
/ statements

return x ;

We will discuss about this when we will study pointers with arrays.

Passing arrays as parameter to function


Now let's see a few examples where we will pass a single array element as argument to a function, a one dimensional
array to a function and a multidimensional array to a function.
Passing a single array element to a function
Let's write a very simple program, where we will declare and define an array of integers in our main() function and
pass one of the array element to a function, which will just print the value of the element.
#include<stdio.h>

void giveMeArray(int a);

int main()

int myArray[] = { 2, 3, 4 };
giveMeArray(myArray[2]); //Passing array element myArray[2] only.

return 0;

void giveMeArray(int a)

printf("%d", a);

Passing a complete One-dimensional array to a function


To understand how this is done, let's write a function to find out average of all the elements of the array and print it.
We will only send in the name of the array as argument, which is nothing but the address of the starting element of the
array, or we can say the starting memory address.
#include<stdio.h>

float findAverage(int marks[]);

int main()

float avg;

int marks[] = {99, 90, 96, 93, 95};

avg = findAverage(marks); // name of the array is passed as argument.

printf("Average marks = %.1f", avg);

return 0;

float findAverage(int marks[])

int i, sum = 0;

float avg;

for (i = 0; i <= 4; i++) {

sum += marks[i];

avg = (sum / 5);

return avg;

}
Passing a Multi-dimensional array to a function
Here again, we will only pass the name of the array as argument.

#include<stdio.h>

void displayArray(int arr[3][3]);

int main()

int arr[3][3], i, j;

printf("Please enter 9 numbers for the array: \n");

for (i = 0; i < 3; ++i)

for (j = 0; j < 3; ++j)

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

/ passing the array as argument

displayArray(arr);

return 0;

void displayArray(int arr[3][3])

int i, j;

printf("The complete array is: \n");

for (i = 0; i < 3; ++i)

/ getting cursor to new line

printf("\n");

for (j = 0; j < 3; ++j)

/ \t is used to provide tab

space printf("%d\t", arr[i][j]);

}
Please enter 9 numbers for the array:

The complete array is:

123

456

789

You might also like