× Back 1D Array 2D Array String
Next Topic → ← Previous Topic

Arrays

One Dimensional

Initialization of 1D array

  • There are two types of initialization of an array.
    1. Compile time initialization → fixed
    2. Run time initialization → dynamic

Compile time initialization

  • When we provide initial value at the time array declaration is known as complie time initialization of array
  • Syntax :
    • data-type name[size] = { element1, element2,... }
  • Example :
    • int arr[5] = {1, 3, 4, 6, 7};
                            
int arr[5] = {1, 2, 3}; // valid statement
int arr[] = {1, 2, 3}; // valid statement
int arr[]; // invalid statement
int arr[5] = {1,2,3,4,5,6,7}; // invalid statement

// first memory is known as base address

int a[5]; // at every index garbage value will be stored 
int a[5] = {}; // at every index 0 will be stored.
int a[6*2] = {1,2,3}; // valid 
int a[13/2] = {3,4}; // valid 
int a[12.5/2]; // invalid 
int a[-3]; // invalid 
                            
                        
  • Note - If the size of the array is missing but the values are given then the size of the array formed will be equal to the number of initializes.
  • Note - If the number of initializes is more than the size of the array then the error of too many initializes is given.

Run time initialization

  • When we provide initial value at the time of execution is known as runtime initialization.
  • We can change the values of array in every different execution.
                            
// runtime initialization program

#include <stdio.h> 
int main()
{
    int arr[10];
    for(int i = 0; i < 10; i++){
        scanf("%d",&arr[i]);
    }
    return 0;
}
                            
                        

Limitations of array

  1. We can only store similar data type values.
  2. While declaring the array passing size of the array is compulsary, and the size must be a constant. Thus there is either shortage or wastage of memory.
  3. Insertion or deletion of elements in an array will require shifting.

Programs

Program to calculate sum of all numbers present in an array.

                            
#include <stdio.h>

int main()
{
    int arr[6] = {2, 5, 6, 7, 8, 22}, sum = 0;
    for (int i = 0; i < 6; i++)
    {
        sum += arr[i];
    }
    printf("Total sum of the array is : %d\n", sum);

    return 0;
}
                            
                        

Program to calculate sum of all even numbers and odd numbers in an array.

                            
#include <stdio.h>

int main()
{
    int arr[6] = {2, 5, 6, 7, 8, 22}, even_sum = 0, odd_sum = 0;
    for (int i = 0; i < 6; i++)
    {
        if (arr[i] % 2 == 0)
        {
            even_sum += arr[i];
        }
        else
        {
            odd_sum += arr[i];
        }
    }
    printf("The sum of even number in the array is : %d\n", even_sum);
    printf("The sum of odd number in the array is : %d\n", odd_sum);

    return 0;
}
                            
                        

Program which calculate sum of all values at even index and odd index in an array

                            
#include <stdio.h>

int main()
{
    int arr[6] = {2, 5, 6, 7, 8, 22}, even_i_sum = 0, odd_i_sum = 0;
    for (int i = 0; i < 6; i++)
    {
        if (i % 2 == 0)
        {
            even_i_sum += arr[i];
        }
        else
        {
            odd_i_sum += arr[i];
        }
    }
    printf("The sum of numbers at even index is : %d\n", even_i_sum);
    printf("The sum of numbers at odd index is : %d\n", odd_i_sum);

    return 0;
}
                            
                        

Program to print the average of n numbers

                            
#include <stdio.h>
    int main()
    {
        int arr[50], n, sum = 0;
        float avg;
        printf("Enter the number of element in array : ");
        scanf("%d", &n);
        printf("Enter the element in the array.\n");
        for (int i = 0; i < n; i++)
        {
            printf("Enter element at %d index : ", i);
            scanf("%d", &arr[i]);
        }
        for (int i = 0; i < n; i++)
        {
            sum += arr[i];
        }
        avg = sum / n;
        printf("The average is : %f", avg);
        return 0;
}
                            
                        

Program to search an element from an array using linear search technique.

                            

                                    #include <stdio.h>

                                    int main()
                                    {
                                       int arr[50], n, search, flag = 0;
                                       printf("Enter the number of element in array : ");
                                       scanf("%d", &n);
                                       printf("Enter the element in the array.\n");
                                       for (int i = 0; i < n; i++)
                                       {
                                          printf("Enter element at %d index : ", i);
                                          scanf("%d", &arr[i]);
                                       }
                                       printf("Enter the element you want to search : ");
                                       scanf("%d", &search);
                                    
                                       for (int i = 0; i < n; i++)
                                       {
                                          if (arr[i] == search)
                                          {
                                             flag = 1;
                                             break;
                                          }
                                       }
                                       if (flag)
                                       {
                                          printf("%d is present\n", search);
                                       }
                                       else
                                       {
                                          printf("%d is not present\n", search);
                                       }
                                    
                                       return 0;
                                    }
                            
                        

Program to insert an element in an array

                            
#include <stdio.h>
int main()
{
    int arr[50], n, pos, element;
    printf("Enter the number of element in array : ");
    scanf("%d", &n);
    printf("Enter the element in the array.\n");
    for (int i = 0; i < n; i++)
    {
        printf("Enter element at %d index : ", i);
        scanf("%d", &arr[i]);
    }

    printf("Give the position index value and the element you want to insert : ");
    scanf("%d%d", &pos, &element);
    // shifting and inserting
    for (int i = n - 1; i >= pos; i--)
    {
        arr[i + 1] = arr[i];
    }
    arr[pos] = element;

    // displaying array
    for (int i = 0; i <= n; i++)
    {
        printf("%d\t", arr[i]);
    }
    return 0;
}
                            
                        

Program to reverse an array

                            
#include <stdio.h>
int main()
{
    int arr[50], rev[50], n, j;
    printf("Enter the number of element in array : ");
    scanf("%d", &n);
    printf("Enter the element in the array.\n");
    for (int i = 0; i < n; i++)
    {
        printf("Enter element at %d index : ", i);
        scanf("%d", &arr[i]);
    }

    // storing reverse of array
    j = n - 1;
    for (int i = 0; i < n; i++)
    {
        rev[i] = arr[j];
        j--;
    }

    // displaying array
    for (int i = 0; i < n; i++)
    {
        printf("%d\t", rev[i]);
    }
    return 0;
}
                            
                        
                            
#include <stdio.h>
int main()
{
    int arr[50], rev[50], n, k, j, temp;
    printf("Enter the number of element in array : ");
    scanf("%d", &n);
    printf("Enter the element in the array.\n");
    for (int i = 0; i < n; i++)
    {
        printf("Enter element at %d index : ", i);
        scanf("%d", &arr[i]);
    }

    j = 0;
    k = n - 1;
    for (int i = 0; i < n / 2; i++)
    {
        temp = arr[j];
        arr[j] = arr[k];
        arr[k] = temp;
        j++;
        k--;
    }

    // displaying array
    for (int i = 0; i < n; i++)
    {
        printf("%d\t", arr[i]);
    }
    return 0;
}
                            
                        

Program to merge two array into third array

                            
#include <stdio.h>
int main()
{
    int arr1[50], arr2[50], merge[50], n1, n2, j = 0;
    printf("Enter the number of element in array one: ");
    scanf("%d", &n1);
    printf("Enter the element in the array.\n");
    for (int i = 0; i < n1; i++)
    {
        printf("Enter element at %d index : ", i);
        scanf("%d", &arr1[i]);
    }
    printf("Enter the number of element in array two: ");
    scanf("%d", &n2);
    printf("Enter the element in the array.\n");
    for (int i = 0; i < n2; i++)
    {
        printf("Enter element at %d index : ", i);
        scanf("%d", &arr2[i]);
    }

    // merging
    for (int i = 0; i < n1 + n2; i++)
    {
        if (i < n1)
        {
            merge[i] = arr1[i];
        }
        else
        {
            merge[i] = arr2[j];
            j++;
        }
    }

    // displaying array
    for (int i = 0; i < n1 + n2; i++)
    {
        printf("%d\t", merge[i]);
    }
    return 0;
}
                            
                        

Program to sum two array into third array

                            
#include <stdio.h>
int main()
{
    int arr1[50] = {0}, arr2[50] = {0}, sum[50], n1, n2, max_size;
    printf("Enter the number of element in array one: ");
    scanf("%d", &n1);
    printf("Enter the element in the array.\n");
    for (int i = 0; i < n1; i++)
    {
        printf("Enter element at %d index : ", i);
        scanf("%d", &arr1[i]);
    }
    printf("Enter the number of element in array two: ");
    scanf("%d", &n2);
    printf("Enter the element in the array.\n");
    for (int i = 0; i < n2; i++)
    {
        printf("Enter element at %d index : ", i);
        scanf("%d", &arr2[i]);
    }

    if (n1 > n2)
        max_size = n1;
    else
        max_size = n2;

    for (int i = 0; i < max_size; i++)
    {
        sum[i] = arr1[1] + arr2[i];
    }

    // displaying array
    for (int i = 0; i < max_size; i++)
    {
        printf("%d\t", sum[i]);
    }
    return 0;
}
                            
                        

2D-Array

                
// the following declaration creates a matrix of 4 rows and 5 columns.
int mat[4][5];
                
            

2D array initialization

                    
int mat[4][3];
int mat[4][3] = {{10,20,30,40},{50,60,70,80},{90,100,110,120}};
int mat[4][3]={10,20,30,40,50,60,70,80,90,100,110,120};
                    
                
                    
Notes 
int mat[][] is invalied because dimensions are not specified
int mat[][] = {1,2,3,4,5,6} is invalid because it is not possible to decide the row and column of the matrix 
int mat[][3] = {1,2,3,4,5,6} is valid
int mat[2][] = {1,2,3,4,5,6} is invalid as column is compulsory in matrix declaration.
                     
                

Programs

                        
#include <stdio.h>
#define row 3
#define col 3
int main()
{
    int ar[row][col], i, j, n;
    printf("Enter the elements of array\n");
    for (i = 0; i < row; i++)
    {
        for (j = 0; j < col; j++)
        {
            printf("Enter at ar[%d][%d] : ", i, j);
            scanf("%d", &ar[i][j]);
        }
    }
    printf("The elements of array\n");
    for (i = 0; i < row; i++)
    {
        for (j = 0; j < col; j++)
        {
            printf(" %d ", ar[i][j]);
        }
        printf("\n");
    }
    if (row == col)
    {
        printf("The lower triangular matrix\n");
        for (i = 0; i < row; i++)
        {
            for (j = 0; j < col; j++)
            {
            if (j <= i)
            {
                printf(" %d ", ar[i][j]);
            }
            }
            printf("\n");
        }
        printf("The upper triangular matrix\n");
        for (i = 0; i < row; i++)
        {
            for (j = 0; j < col; j++)
            {
            if (j >= i)
            {
                printf("  %d", ar[i][j]);
            }
            else
            {
                printf("   ");
            }
            }
            printf("\n");
        }
    }
    else
        printf("Can't calculate the upper/lower triangle in matrix");
    return 0;
}
                        
                    

String (Character Array)

                
char s[10] = {'h','e','l','l','o','\0'};
                
            
                
note - The null '\0' looks as if two characters when typed but the compiler treats it as a single character. It is an escape sequence.
                
            

Character array initialization

                    
char s[10];
char s[6] = {'h','a','r','r','y','\0'};
char s[6] = {'h','a','r','r','y'};
above the null character is missing which is added automatically the compiler at the end of the string.
char s[6] = "harry";
char s[0] = {'h','a','r','r','y','\0'};

note - the size of the string should be equal to the maximum number of characters in the string + 1.
- The initialization of the string without the mentioning of size is also permitted, as in the integer array.
   In such sace the array size will be automatically based on the number of elements initialized.
                    
                

String Input

                    
scanf("%s",name);
                    
                
                    
char name[10];
gets(name);
                    
                
                    
puts(name);
                    
                

String functions

strlen()

  • It is used to return the length of the string
  •                             
    char name[] = "Henry";
    printf("%d", (int)strlen(name)); // 5
                                
                            

strcpy(str1, str2)

  • this function is used to copy the contents of the string str1 into string str2.
                        
char str1[] = "Hello";
char str2[10];
strcpy(str1, str2);
// str2 -> "Hello"
                        
                    

strcat(str1, str2)

  • It is used to concatenate string str2 onto the end of the string str1.
                        
char fullname[30] = "Harry";
char lastname[10] = " Potter";
strcat(fullname, lastname);
printf("%s", fullname);
                        
                    

strcmp(str1, str2)

  • It is used to analyse and compare the string str1 and str2.
  • Returns 0 if str1 and str2 are the same, less than 0 if str1<str2 and greater than 0 is str1>str2

strchr(str1, ch)

  • It is used to discover the foremost event or occurence of a specified character within the actual string.