Arrays and String

By Paribesh Sapkota

Arrays

An array is a collection of similar type of data items treated as Single UL F nets to stare related data under the same name with an index, also known as a subscript which helps to access individual array element. Array, data type may be int, float, char etc, depending upon the nature of problems.

Characteristics of Array

All the array elements share the common name.

The elements of array are stored in contiguous memory locations.

By declaring or using array, program becomes short and simple which handles large volume of similar kinds of data items.

We put the array size of fixed length as required that means once the size is declared then the size will be fixed at the execution time of the program, so called static type.

 

We can randomly access to every element using numeric index, index starts from 0 and ends at size-1.

Advantages of Array

It is easier for handling similar types of data in a program.

It is efficient for solving problems like sorting, searching, indexing etc. It is very close to matrix, therefore it is easy for solving matrix related problems.

Graphic is an array of pixels so, graphics manipulation can be easily be done using array.

Disadvantages of Array

It is not possible to hold dissimilar type of data in an array.

It is difficult to visualize the multi-dimensional array.

It is static in nature so it is difficult to define the size of array during running time.

Types of Array

There are two types of array which are as follows.

1. One Dimensional Array: An array which has only one subscript is named as one dimensional array, a subscript is a number of large bracket in which we put the size of the array.

Syntax of 1D Array in C

array_name [size];
// C Program to illustrate the use of 1D array
#include <stdio.h>
 
int main()
{
 
    // 1d array declaration
    int arr[5];
 
    // 1d array initialization using for loop
    for (int i = 0; i < 5; i++) {
        arr[i] = i * i - 2 * i + 1;
    }
 
    printf("Elements of Array: ");
    // printing 1d array by traversing using for loop
    for (int i = 0; i < 5; i++) {
        printf("%d ", arr[i]);
    }
 
    return 0;
}

Output

Elements of Array: 1 0 1 4 9 

2. Multi Dimensional Array: An array which has more than one subscript is named as multi dimensional array, subscripts define each dimensions of the array.

A. Two-Dimensional Array in C

A Two-Dimensional array or 2D array in C is an array that has exactly two dimensions. They can be visualized in the form of rows and columns organized in a two-dimensional plane.

Syntax of 2D Array in C

array_name[size1] [size2];

Here,

  • size1: Size of the first dimension.
  • size2: Size of the second dimension.
    // 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
        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 3; j++) {
                printf("%d ",arr[i][j]);
            }
            printf("\n");
        }
     
        return 0;
    }
    Output
    2D Array:
    10 20 30 
    40 50 60 
    
    

    . Three-Dimensional Array in C

    Another popular form of a multi-dimensional array is Three Dimensional Array or 3D Array. A 3D array 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.

    Syntax of 3D Array in C

    array_name [size1] [size2] [size3];
    // 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++) {
                for (int k = 0; k < 2; k++) {
                    printf("%d ", arr[i][j][k]);
                }
                printf("\n");
            }
            printf("\n \n");
        }
        return 0;
    }
    Output
    10 20 
    30 40 
    
     
    50 60 
    0 0 
    

     

 

Array Declaration

In C, we have to declare the array like any other variable before using it. 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 of Array Declaration

data_type array_name [size];
         or
data_type array_name [size1] [size2]...[sizeN];

where N is the number of dimensions.

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

 

C Array Initialization

Initialization in C is the process to assign some initial value to the variable. 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. There are multiple ways in which we can initialize an array in C.

 

1. Array Initialization with Declaration

 

In this method, we initialize the array along with its 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};
#include <stdio.h>

int main() {
    // Initializing an array of integers with declaration
    int numbers[5] = {10, 20, 30, 40, 50};

    // Printing the elements of the array
    printf("The elements of the array are: ");
    for(int i = 0; i < 5; ++i) {
        printf("%d ", numbers[i]);
    }
    printf("\n");

    return 0;
}

 

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 arrays is 5 which is automatically deduced by the compiler.

#include <stdio.h>

int main() {
    // Initializing an array of integers without specifying size
    int numbers[] = {10, 20, 30, 40, 50};

    // Getting the size of the array
    int size = sizeof(numbers) / sizeof(numbers[0]);

    // Printing the elements of the array
    printf("The elements of the array are: ");
    for(int i = 0; i < size; ++i) {
        printf("%d ", numbers[i]);
    }
    printf("\n");

    return 0;
}

 

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.

for (int i = 0; i < N; i++) {
    array_name[i] = valuei;
}
#include <stdio.h>

int main() {
    // Declaration of an array of integers
    int numbers[5];

    // Initializing the array using a for loop
    for(int i = 0; i < 5; ++i) {
        numbers[i] = (i + 1) * 10;
    }

    // Printing the elements of the array
    printf("The elements of the array are: ");
    for(int i = 0; i < 5; ++i) {
        printf("%d ", numbers[i]);
    }
    printf("\n");

    return 0;
}

Memory allocation of an array

All the data elements of an array are stored at contiguous locations in the main memory. The name of the array represents the base address or the address of the first element in the main memory. Each element of the array is represented by proper indexing.

We can define the indexing of an array in the below ways –

  1. 0 (zero-based indexing): The first element of the array will be arr[0].
  2. 1 (one-based indexing): The first element of the array will be arr[1].
  3. n (n – based indexing): The first element of the array can reside at any random index number.

 

In the above image, we have shown the memory allocation of an array arr of size 5. The array follows a 0-based indexing approach. The base address of the array is 100 bytes. It is the address of arr[0]. Here, the size of the data type used is 4 bytes; therefore, each element will take 4 bytes in the memory.

#include <stdio.h>

int main() {
    // Declaration and initialization of an array of integers
    int numbers[5] = {10, 20, 30, 40, 50};

    // Printing the memory representation of the array
    printf("Memory representation of the array:\n");
    for(int i = 0; i < 5; ++i) {
        printf("&numbers[%d] = %p, numbers[%d] = %d\n", i, (void *)&numbers[i], i, numbers[i]);
    }

    return 0;
}

Here’s a sample output:

Memory representation of the array:
&numbers[0] = 0x7ffc2e1f3b30, numbers[0] = 10
&numbers[1] = 0x7ffc2e1f3b34, numbers[1] = 20
&numbers[2] = 0x7ffc2e1f3b38, numbers[2] = 30
&numbers[3] = 0x7ffc2e1f3b3c, numbers[3] = 40
&numbers[4] = 0x7ffc2e1f3b40, numbers[4] = 50

Why do we need Arrays?

We can use normal variables (v1, v2, v3, ..) when we have a small number of objects, but if we want to store a large number of instances, it becomes difficult to manage them with normal variables. The idea of an array is to represent many instances in one variable.

5. How can we determine the size of the C array?

We can determine the size of the Array using sizeof Operator in C. We first get the size of the whole array and divide it by the size of each element type.

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

  1. char ch[10]={‘j’‘a’‘v’‘a’‘t’‘p’‘o’‘i’‘n’‘t’‘\0’};

While declaring string, size is not mandatory. So we can write the above code as given below:

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

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]={'p', 'a', 'r', 'i', 'b', 'e', 's', 'h', '\0'};    
   char ch2[11]="paribesh";    
    
   printf("Char Array Value is: %s\n", ch);    
   printf("String Literal Value is: %s\n", ch2);    
 return 0;    
}

Output

Char Array Value is: paribesh
String Literal Value is: paribesh

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.

  • By using the length of string
  • By using the null character.
    #include <stdio.h>
    
    int main() {
        char str[] = "Hello, World!";
    
        printf("Traversing the string using the null character:\n");
        for(int i = 0; str[i] != '\0'; ++i) {
            printf("%c ", str[i]);
        }
        printf("\n");
    
        return 0;
    }
    

    Both of these programs output the same result, which is traversing the string “Hello, World!” character by character:

    Traversing the string using its length:
    H e l l o ,   W o r l d ! 
    
    Traversing the string using the null character:
    H e l l o ,   W o r l d ! 
    

    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')  
        {  
            count ++;  
        }  
        i++;  
    }  
    printf("The number of vowels %d",count);  
}

Output

The number of vowels 4
String Library functions
The predefined functions which are designed to handle strings are available in the library string.h. They are −

  1. strlen(): This function returns the length of the string, i.e., the number of characters in the string excluding the null character.

    Syntax

    int strlen (string name)
    #include <stdio.h>
    #include <string.h>
    
    int main() {
        char str[] = "Hello";
        int length = strlen(str);
        printf("Length of the string is: %d\n", length);
        return 0;
    }
    
    1. strcmp(): This function compares two strings. It returns 0 if both strings are equal, a positive value if the first string is greater than the second, and a negative value if the first string is smaller than the second.

      Syntax

      int strcmp (string1, string2);
      //If the difference is equal to zero, then string1 = string2
      //If the difference is positive, then string1 > string2
      //If the difference is negative, then string1 < string2
      #include <stdio.h>
      #include <string.h>
      
      int main() {
          char str1[] = "Hello";
          char str2[] = "Hello";
          int result = strcmp(str1, str2);
          printf("Result of comparison: %d\n", result);
          return 0;
      }
      
      1. strcpy(): This function copies the contents of one string into another.

        Syntax

        strcpy (Destination string, Source String);
        #include <stdio.h>
        #include <string.h>
        
        int main() {
            char str1[20];
            char str2[] = "Hello";
            strcpy(str1, str2);
            printf("Copied string is: %s\n", str1);
            return 0;
        }
        
        1. strncmp(): This function compares the first n characters of two strings.

          Syntax

          strncmp ( string1, string2,2)
          #include <stdio.h>
          #include <string.h>
          
          int main() {
              char str1[] = "Hello";
              char str2[] = "World";
              int result = strncmp(str1, str2, 3);
              printf("Result of comparison: %d\n", result);
              return 0;
          }
          

           

        2. strncpy(): This function copies the first n characters of one string into another.

          Syntax

          strncpy (Destination string, Source String, n);
          #include <stdio.h>
          #include <string.h>
          
          int main() {
              char str1[20];
              char str2[] = "Hello";
              strncpy(str1, str2, 3);
              str1[3] = '\0'; // Null terminate the string
              printf("Copied string is: %s\n", str1);
              return 0;
          }
          
        3. strrev(): This function reverses the given string.

          Syntax

          strrev (string)
          #include <stdio.h>
          #include <string.h>
          
          int main() {
              char str[] = "Hello";
              strrev(str);
              printf("Reversed string is: %s\n", str);
              return 0;
          }
          
          1. strcat(): This function concatenates two strings.

            Syntax

            strcat (Destination String, Source string);
            #include <stdio.h>
            #include <string.h>
            
            int main() {
                char str1[20] = "Hello";
                char str2[] = " World!";
                strcat(str1, str2);
                printf("Concatenated string is: %s\n", str1);
                return 0;
            }
            
            1. strstr(): This function finds the first occurrence of a substring in a string.
              #include <stdio.h>
              #include <string.h>
              
              int main() {
                  char str[] = "Hello, World!";
                  char *sub = strstr(str, "World");
                  if(sub != NULL) {
                      printf("Substring found at position: %ld\n", sub - str);
                  } else {
                      printf("Substring not found\n");
                  }
                  return 0;
              }
              
              1. strncat(): This function concatenates the first n characters of one string to another.

                Syntax

                strncat (Destination String, Source string,n);
                #include <stdio.h>
                #include <string.h>
                
                int main() {
                    char str1[20] = "Hello";
                    char str2[] = " World!";
                    strncat(str1, str2, 5);
                    printf("Concatenated string is: %s\n", str1);
                    return 0;
                }
                

                 

Read and write strings

To read a string in C, you can use the scanf() function with the %s format specifier. However, using %s stops reading the string when it encounters whitespace (space, tab, newline). To read a whole line, you can use the %[^\n] format specifier.

#include <stdio.h>

int main() {
    char str[100];

    // Reading a string from the user
    printf("Enter a string: ");
    scanf("%[^\n]", str);
    // %[^\n] tells scanf to read until a newline character is encountered

    // Writing the string to the console
    printf("You entered: %s\n", str);

    return 0;
}

Writing a String:

To write a string in C, you can use the printf() function with the %s format specifier.

#include <stdio.h>

int main() {
    char str[] = "Hello, World!";

    // Writing the string to the console
    printf("The string is: %s\n", str);

    return 0;
}

 

Important Questions
Comments
Discussion
0 Comments
  Loading . . .