C Array
An array is defined as the collection of similar type of data items stored at
contiguous memory locations. Arrays are the derived data type in C
programming language which 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.
C array is beneficial if you have to store similar elements. For example, if we
want to store the marks of a student in 6 subjects, then we don't need to
define different variables for the marks in the different subject. Instead of
that, we can define an array which 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 Array
The array contains the following properties.
o Each element of an array is of 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 since we can
calculate the address of each element of the array with the given base
address and the size of the data element.
Advantage of C Array
1) Code Optimization: Less code to the access the data.
2) Ease of traversing: By using the for loop, we can retrieve the elements
of an array easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines
of code only.
4) Random Access: We can access any element randomly using the array.
Disadvantage of C Array
1) Fixed Size: Whatever size, we define at the time of declaration of the
array, we can't exceed the limit. So, it doesn't grow the size dynamically like
LinkedList which we will learn later.
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
1. #include<stdio.h>
2. int main(){
3. int i=0;
4. int marks[5];//declaration of array
5. marks[0]=80;//initialization of array
6. marks[1]=60;
7. marks[2]=70;
8. marks[3]=85;
9. marks[4]=75;
10. //traversal of array
11. for(i=0;i<5;i++){
12. printf("%d \n",marks[i]);
13. }//end of for loop
14. return 0;
15. }
Output
80
60
70
85
75
C Array: Declaration with Initialization
We can initialize the c array at the time of declaration. Let's see the code.
1. int marks[5]={20,30,40,50,60};
In such case, there is no requirement to define the size. So it may also
be written as the following code.
1. int marks[]={20,30,40,50,60};
Let's see the C program to declare and initialize the array in C.
1. #include<stdio.h>
2. int main(){
3. int i=0;
4. int marks[5]={20,30,40,50,60};//declaration and initialization 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
C Array Example: Sorting an array
In the following program, we are using bubble sort method to sort the array
in ascending order.
1. #include<stdio.h>
2. void main ()
3. {
4. int i, j,temp;
5. int a[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
6. for(i = 0; i<10; i++)
7. {
8. for(j = i+1; j<10; j++)
9. {
10. if(a[j] > a[i])
11. {
12. temp = a[i];
13. a[i] = a[j];
14. a[j] = temp;
15. }
16. }
17. }
18. printf("Printing Sorted Element List ...\n");
19. for(i = 0; i<10; i++)
20. {
21. printf("%d\n",a[i]);
22. }
23. }
Program to print the largest and second largest element of the
array.
1. #include<stdio.h>
2. void main ()
3. {
4. int arr[100],i,n,largest,sec_largest;
5. printf("Enter the size of the array?");
6. scanf("%d",&n);
7. printf("Enter the elements of the array?");
8. for(i = 0; i<n; i++)
9. {
10. scanf("%d",&arr[i]);
11. }
12. largest = arr[0];
13. sec_largest = arr[1];
14. for(i=0;i<n;i++)
15. {
16. if(arr[i]>largest)
17. {
18. sec_largest = largest;
19. largest = arr[i];
20. }
21. else if (arr[i]>sec_largest && arr[i]!=largest)
22. {
23. sec_largest=arr[i];
24. }
25. }
26. printf("largest = %d, second largest = %d",largest,sec_largest);
27.
28. }
Two Dimensional Array in C
The two-dimensional array can be defined as an array of arrays. The 2D
array is organized as matrices which can be represented as the collection of
rows and columns. However, 2D arrays are created to implement a relational
database lookalike data structure. It provides ease of holding the bulk of
data at once which can be passed to any number of functions wherever
required.
Declaration of two dimensional Array in C
The syntax to declare the 2D array is given below.
1. data_type array_name[rows][columns];
Consider the following example.
1. int twodimen[4][3];
Here, 4 is the number of rows, and 3 is the number of columns.
Initialization of 2D Array in C
In the 1D array, we don't need to specify the size of the array if the
declaration and initialization are being done simultaneously. However, this
will not work with 2D arrays. We will have to define at least the second
dimension of the array. The two-dimensional array can be declared and
defined in the following way.
1. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
Two-dimensional array example in C
1. #include<stdio.h>
2. int main(){
3. int i=0,j=0;
4. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
5. //traversing 2D array
6. for(i=0;i<4;i++){
7. for(j=0;j<3;j++){
8. printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
9. }//end of j
10. }//end of i
11. return 0;
12. }
Output
arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6
C 2D array example: Storing elements in a matrix and printing it.
1. #include <stdio.h>
2. void main ()
3. {
4. int arr[3][3],i,j;
5. for (i=0;i<3;i++)
6. {
7. for (j=0;j<3;j++)
8. {
9. printf("Enter a[%d][%d]: ",i,j);
10. scanf("%d",&arr[i][j]);
11. }
12. }
13. printf("\n printing the elements ....\n");
14. for(i=0;i<3;i++)
15. {
16. printf("\n");
17. for (j=0;j<3;j++)
18. {
19. printf("%d\t",arr[i][j]);
20. }
21. }
22. }
Output
Enter a[0][0]: 56
Enter a[0][1]: 10
Enter a[0][2]: 30
Enter a[1][0]: 34
Enter a[1][1]: 21
Enter a[1][2]: 34
Enter a[2][0]: 45
Enter a[2][1]: 56
Enter a[2][2]: 78
printing the elements ....
56 10 30
34 21 34
45 56 78
Return an Array in C
What is an Array?
An array is a type of data structure that stores a fixed-size of a homogeneous
collection of data. In short, we can say that array is a collection of variables
of the same type.
For example, if we want to declare 'n' number of variables, n1, n2...n., if we
create all these variables individually, then it becomes a very tedious task. In
such a case, we create an array of variables having the same type. Each
element of an array can be accessed using an index of the element.
Let's first see 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. printf("Elements of array are : ");
5. for(int i=0;i<5;i++)
6. {
7. printf("%d ", arr[i]);
8. }
9. }
10.int main()
11.{
12. int arr[5]={45,67,34,78,90};
13. getarray(arr);
14. return 0;
15.}
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
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",&y.arr[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;x.arr[i]!='\0';i++)
22. {
23. printf("%d ", x.arr[i]);
24. }
25. return 0;
26.}
Output
C Strings
The string can be defined as the one-dimensional array of characters terminated by a
null ('\0'). The character array or the string is used to manipulate text such as word or
sentences. Each character in the array occupies one byte of memory, and the last
character must always be 0. The termination character ('\0') is important in a string
since it is the only way to identify where the string ends. When we define a string as
char s[10], the character s[10] is implicitly initialized with the null in the memory.
There are two ways to declare a string in c language.
1. By char array
2. By string literal
Let's see the example of declaring string by char array in C language.
char ch[10]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
As we know, array index starts from 0, so it will be represented as in the figure given
below.
While declaring string, size is not mandatory. So we can write the above code as given
below:
char ch[]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
We can also define the string by the string literal in C language. For example:
char ch[]="javatpoint";
In such case, '\0' will be appended at the end of the string by the compiler.
Difference between char array and string literal
There are two main differences between char array and literal.
o We need to add the null character '\0' at the end of the array by ourself whereas, it is
appended internally by the compiler in the case of the character array.
o The string literal cannot be reassigned to another set of characters whereas, we can
reassign the characters of the array.
String Example in C
Let's see a simple example where a string is declared and being printed. The '%s' is
used as a format specifier for the string in c language.
#include<stdio.h>
#include <string.h>
int main(){
char ch[11]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
char ch2[11]="javatpoint";
printf("Char Array Value is: %s\n", ch);
printf("String Literal Value is: %s\n", ch2);
return 0;
10.}
Output
Char Array Value is: javatpoint
String Literal Value is: javatpoint
Traversing String
Traversing the string is one of the most important aspects in any of the programming
languages. We may need to manipulate a very large text which can be done by
traversing the text. Traversing string is somewhat different from the traversing an
integer array. We need to know the length of the array to traverse an integer array,
whereas we may use the null character in the case of string to identify the end the
string and terminate the loop.
Hence, there are two ways to traverse a string.
o By using the length of string
o By using the null character.
Let's discuss each one of them.
Using the length of string
Let's see an example of counting the number of vowels in a string.
#include<stdio.h>
void main ()
{
char s[11] = "javatpoint";
int i = 0;
int count = 0;
while(i<11)
{
if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'u' || s[i] == 'o')
10. {
11. count ++;
12. }
13. i++;
14. }
15. printf("The number of vowels %d",count);
16.}
Output
The number of vowels 4
Using the null character
Let's see the same example of counting the number of vowels by using the null
character.
#include<stdio.h>
void main ()
{
char s[11] = "javatpoint";
int i = 0;
int count = 0;
while(s[i] != NULL)
{
if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'u' || s[i] == 'o')
10. {
11. count ++;
12. }
13. i++;
14. }
15. printf("The number of vowels %d",count);
16.}
Output
The number of vowels 4
Accepting string as the input
Till now, we have used scanf to accept the input from the user. However, it can also be
used in the case of strings but with a different scenario. Consider the below code which
stores the string while space is encountered.
#include<stdio.h>
void main ()
{
char s[20];
printf("Enter the string?");
scanf("%s",s);
printf("You entered %s",s);
}
Output
Enter the string?javatpoint is the best
You entered javatpoint
It is clear from the output that, the above code will not work for space separated strings.
To make this code working for the space separated strings, the minor changed required
in the scanf function, i.e., instead of writing scanf("%s",s), we must write: scanf("%[^\
n]s",s) which instructs the compiler to store the string s while the new line (\n) is
encountered. Let's consider the following example to store the space-separated strings.
#include<stdio.h>
void main ()
{
char s[20];
printf("Enter the string?");
scanf("%[^\n]s",s);
printf("You entered %s",s);
}
Output
Enter the string?javatpoint is the best
You entered javatpoint is the best
Here we must also notice that we do not need to use address of (&) operator in scanf to
store a string since string s is an array of characters and the name of the array, i.e., s
indicates the base address of the string (character array) therefore we need not use &
with it.
Some important points
However, there are the following points which must be noticed while entering the
strings by using scanf.
o The compiler doesn't perform bounds checking on the character array. Hence, there can
be a case where the length of the string can exceed the dimension of the character array
which may always overwrite some important data.
o Instead of using scanf, we may use gets() which is an inbuilt function defined in a header
file string.h. The gets() is capable of receiving only one string at a time.
Pointers with strings
We have used pointers with the array, functions, and primitive data types so far.
However, pointers can be used to point to the strings. There are various advantages of
using pointers to point strings. Let us consider the following example to access the
string via the pointer.
#include<stdio.h>
void main ()
{
char s[11] = "javatpoint";
char *p = s; // pointer p is pointing to string s.
printf("%s",p); // the string javatpoint is printed if we print p.
}
Output
javatpoint
As we know that string is an array of characters, the pointers can be used in the same
way they were used with arrays. In the above example, p is declared as a pointer to the
array of characters s. P affects similar to s since s is the base address of the string and
treated as a pointer internally. However, we can not change the content of s or copy the
content of s into another string directly. For this purpose, we need to use the pointers to
store the strings. In the following example, we have shown the use of pointers to copy
the content of a string into another.
#include<stdio.h>
void main ()
{
char *p = "hello javatpoint";
printf("String p: %s\n",p);
char *q;
printf("copying the content of p into q...\n");
q = p;
printf("String q: %s\n",q);
10.}
Output
String p: hello javatpoint
copying the content of p into q...
String q: hello javatpoint
Once a string is defined, it cannot be reassigned to another set of characters. However,
using pointers, we can assign the set of characters to the string. Consider the following
example.
#include<stdio.h>
void main ()
{
char *p = "hello javatpoint";
printf("Before assigning: %s\n",p);
p = "hello";
printf("After assigning: %s\n",p);
}
Output
Before assigning: hello javatpoint
After assigning: hello
C gets() and puts() functions
The gets() and puts() are declared in the header file stdio.h. Both the
functions are involved in the input/output operations of the strings.
C gets() function
The gets() function enables the user to enter some characters followed by
the enter key. All the characters entered by the user get stored in a
character array. The null character is added to the array to make it a string.
The gets() allows the user to enter the space-separated strings. It returns the
string entered by the user.
Declaration
1. char[] gets(char[]);
Reading string using gets()
1. #include<stdio.h>
2. void main ()
3. {
4. char s[30];
5. printf("Enter the string? ");
6. gets(s);
7. printf("You entered %s",s);
8. }
Output
Enter the string?
javatpoint is the best
You entered javatpoint is the best
The gets() function is risky to use since it doesn't perform any array bound
checking and keep reading the characters until the new line (enter) is
encountered. It suffers from buffer overflow, which can be avoided by using
fgets(). The fgets() makes sure that not more than the maximum limit of
characters are read. Consider the following example.
1. #include<stdio.h>
2. void main()
3. {
4. char str[20];
5. printf("Enter the string? ");
6. fgets(str, 20, stdin);
7. printf("%s", str);
8. }
Output
Enter the string? javatpoint is the best website
javatpoint is the b
C puts() function
The puts() function is very much similar to printf() function. The puts()
function is used to print the string on the console which is previously read by
using gets() or scanf() function. The puts() function returns an integer value
representing the number of characters being printed on the console. Since, it
prints an additional newline character with the string, which moves the
cursor to the new line on the console, the integer value returned by puts()
will always be equal to the number of characters present in the string plus 1.
Declaration
1. int puts(char[])
C String Functions
There are many important string functions defined in "string.h" library.
No. Function Description
1) strlen(string_name) returns the length of string name.
2) strcpy(destination, copies the contents of source string to destination
source) string.
3) strcat(first_string, concats or joins first string with second string. The
second_string) result of the string is stored in first string.
4) strcmp(first_string, compares the first string with second string. If both
second_string) strings are same, it returns 0.
5) strrev(string) returns reverse string.
6) strlwr(string) returns string characters in lowercase.
7) strupr(string) returns string characters in uppercase.
C String Length: strlen() function
The strlen() function returns the length of the given string. It doesn't count
null character '\0'.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
5. printf("Length of string is: %d",strlen(ch));
6. return 0;
7. }
Output:
Length of string is: 10
C Copy String: strcpy()
The strcpy(destination, source) function copies the source string in
destination.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
5. char ch2[20];
6. strcpy(ch2,ch);
7. printf("Value of second string is: %s",ch2);
8. return 0;
9. }
Output:
Value of second string is: javatpoint
C String Concatenation: strcat()
The strcat(first_string, second_string) function concatenates two strings and
result is returned to first_string.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char ch[10]={'h', 'e', 'l', 'l', 'o', '\0'};
5. char ch2[10]={'c', '\0'};
6. strcat(ch,ch2);
7. printf("Value of first string is: %s",ch);
8. return 0;
9. }
Output:
Value of first string is: helloc
C Compare String: strcmp()
The strcmp(first_string, second_string) function compares two string and
returns 0 if both strings are equal.
Here, we are using gets() function which reads string from the console.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str1[20],str2[20];
5. printf("Enter 1st string: ");
6. gets(str1);//reads string from console
7. printf("Enter 2nd string: ");
8. gets(str2);
9. if(strcmp(str1,str2)==0)
10. printf("Strings are equal");
11. else
12. printf("Strings are not equal");
13. return 0;
14.}
Output:
Enter 1st string: hello
Enter 2nd string: hello
Strings are equal
C Reverse String: strrev()
The strrev(string) function returns reverse of the given string. Let's see a
simple example of strrev() function.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str[20];
5. printf("Enter string: ");
6. gets(str);//reads string from console
7. printf("String is: %s",str);
8. printf("\nReverse String is: %s",strrev(str));
9. return 0;
10.}
Output:
Enter string: javatpoint
String is: javatpoint
Reverse String is: tnioptavaj
C String Lowercase: strlwr()
The strlwr(string) function returns string characters in lowercase. Let's see a
simple example of strlwr() function.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str[20];
5. printf("Enter string: ");
6. gets(str);//reads string from console
7. printf("String is: %s",str);
8. printf("\nLower String is: %s",strlwr(str));
9. return 0;
10.}
Output:
Enter string: JAVATpoint
String is: JAVATpoint
Lower String is: javatpoint
C String Uppercase: strupr()
The strupr(string) function returns string characters in uppercase. Let's see a
simple example of strupr() function.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str[20];
5. printf("Enter string: ");
6. gets(str);//reads string from console
7. printf("String is: %s",str);
8. printf("\nUpper String is: %s",strupr(str));
9. return 0;
10.}
Output:
Enter string: javatpoint
String is: javatpoint
Upper String is: JAVATPOINT
C String strstr()
The strstr() function returns pointer to the first occurrence of the matched
string in the given string. It is used to return substring from first match till
the last character.
Syntax:
1. char *strstr(const char *string, const char *match)
String strstr() parameters
string: It represents the full string from where substring will be searched.
match: It represents the substring to be searched in the full string.
String strstr() example
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str[100]="this is javatpoint with c and java";
5. char *sub;
6. sub=strstr(str,"java");
7. printf("\nSubstring is: %s",sub);
8. return 0;
9. }
Output:
javatpoint with c and java