Arrays

Introduction to Arrays:

  • An array is a group of liked-typed variables. Its unique index indicates each element in an array. 
  • It is used to group related information.
  • Every specific element in an array is accessed by using an index. 
  • In the C language, all arrays have contiguous memory locations. 
  • The lowest address in an array corresponds to the first element, and the highest address corresponds to the last element.
  • Arrays can have one to several dimensions.

Advantages of Arrays:

   (a)Simple and easy to use.

   (b)Faster access to the elements.

   (c)Ease of sorting.

   (d)Traversal becomes easy.

Disadvantages of Arrays:

   (a)Fixed size.

   (b)One block allocation.

   (c)Position-based insertion is complex.

Syntax:

                type var_name[size]; 

               Here, type indicates the base type of the array, which is the type of each element in the array, and size defines how many elements the array will hold.

Example:

                double balance[100];

Representation of an Array:

40.0

71.2

54.7

68.1

0.79

Indexes:              0                      1                        2                        3                        4           

Array initialization:

Arrays can be initialized in three different ways:

  • Firstly, by accessing each individual element.

                    int [] my_Array = new int[4];

                    my_Array[0]=5;

                    my_Array[1]=7;

                    my_Array[2]=4;

                    my_Array[3]=2;

  • Secondly, we can initialize the array by using the collection initializer.

                    int [ ] my_Array = new int[4] {5,7,4,2}

  • Finally, using the collection initializer in another way.

                    int [ ] my_Array = {5,7,4,2}

Types of Arrays:

One-Dimensional (1d) Array:

  • The array in which only one subscript specification is used to specify a particular element  is called One dimensional array.
  • The array element can individually accessed by specifying the position of the index value of the component.

Example:

                Int a[3];

Program:

#include<stdio.h>
int main()
{
    int a[7];// array declaration
    a[0]=87;// array initialization
    a[1]=10;
    a[2]=80;
    a[3]=95;
    a[4]=65;
    a[5]=13;
    a[6]=11;
    //traversal of array
    printf("Elements of Array are:\n");
    for(int x=0;x<7;x++)
    {
        printf(" %d\n",a[x]);
    }
    return 0;
}
Output:
Elements of Array are:
 87
 10
 80
 95
 65
 13
 11
Two-Dimensional (2d) Array:
  • C language supports multidimensional arrays.
  • The most simplistic form of the multidimensional array is the two-dimensional array.
  • A two-dimensional array is, essentially, an array of one-dimensional arrays.

Example:

                    a[5][10];

                    Here, ‘a’ is the two-dimensional integer array of size 5,10.

  • The Two-dimensional arrays are stored in a row-column matrix, where the left index indicates the row and the right indicates the column.

Program:

#include<stdio.h>
int main()
{
    int i=0,j=0;
    int arr[5][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6},{5,6,7}};
    for(i=0;i<5;i++)
    {
        for(j=0;j<3;j++)
        {
            printf("arr[%d] [%d] = %d\n",i,j,arr[i][j]);
        }
    }
    return 0;
}
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
arr[4] [0] = 5
arr[4] [1] = 6
arr[4] [2] = 7
Multi-Dimensional (nd) Array:
  • Multidimensional Arrays in C language allows arrays of more than two dimensions.

    Syntax:

                    type name[size1][size2][size3] . . .[sizeN];

  • Generally, arrays of more than three dimensions are not often used because they require more memory.
  • For example, a four-dimensional char array with dimensions 11,6,9,10 requires 11 * 6 *9 *10 or 5,940 bytes of memory.
  • If the fifth dimension of size 10 is added to the preceding array, 59,400 bytes would be required for storage. i.e., as the number of dimensions increases, the storage also needed increases exponentially.
  • Accessing an element in a multi-dimensional array can be slower when compared to accessing an element in a single-dimension array.
  • The initialization of a three-Dimensional array is similar to a two-dimensional array.
  • The only difference is that as the number of dimensions of an array increases, the number of nested braces will also increase.·  

Example:

int a [2][3][4] = {{{1,2,4,6}, {3,8,0,1}, {45,12,5,9}},                                                                     {{3,4,6,8}, {1,3,9,0}, {12,5,9,8}}};

Program:

// storing and printing 8 values entered by the user
#include <stdio.h>
int main()
{
  int a[2][2][2];
  printf("Enter 8 values: \n");
  for (int i = 0; i < 2; ++i)
  {
    for (int j = 0; j < 2; ++j)
    {
      for (int k = 0; k < 2; ++k)
      {
        scanf("%d", &a[i][j][k]);
      }
    }
  }
  // Printing values with the proper index.
  printf("\nDisplaying values:\n");
  for (int i = 0; i < 2; ++i)
  {
    for (int j = 0; j < 2; ++j)
    {
      for (int k = 0; k < 2; ++k)
      {
        printf("a [%d][%d][%d] = %d\n", i, j, k, a [i][j][k]);
      }
    }
  }
  return 0;
}
Output:
Enter 8 values:
0
1
2
3
4
5
6
7

Displaying values:
a [0][0][0] = 0
a [0][0][1] = 1
a [0][1][0] = 2
a [0][1][1] = 3
a [1][0][0] = 4
a [1][0][1] = 5
a [1][1][0] = 6
a [1][1][1] = 7
Pointers
  • A pointer is defined as a variable that holds the address (memory address) of another variable. 
  • Suppose, if one variable holds the address of another variable, then the first variable is said to be pointing to the second variable.
  • A pointer declaration contains a base type, * and the variable name. 

          Syntax:

                           type *a; 

                         Where ‘a’ is the variable and type is the type of object to which the pointer points.

  • Technically we can say that any pointer can point anywhere in the memory.

Pointer Operators:

          There are two pointer operators:

                    (1) & 

                    (2) *

  • The ‘&’ Operator is a unary operator which returns the memory address of its operand. 

          Note: A unary operator only requires one operand. 

           Example:

                               m = &a; 

                               where ‘m’ is the memory address of the variable ‘a’. 

  • This memory address is the computer’s internal location of the variable.
  • This memory address has nothing to do with the value of ‘a’.
  • We can think of ‘&’ Operator as returning “the address of.” 
  • Therefore, we can verbalize the above example as “m receives the address of a.” 
  • The second Operator, ‘*’, is the complement of the ‘&’ Operator.
  • The ‘*’ Operator is a unary operator which returns the value located at the address that follows. 

Example:

                    If ‘m’ contains the memory address of the variable ‘a’, x= *m; places the value of an into x.

Program:

#include<stdio.h>
int main()
{
    int a = 20;
    int *x;
    x = &a; /*storing the address of var in pointer variable*/
    printf("Address of variable: %x\n", &a);
    printf("Address stored in x variable: %x\n", x);
    /*accessing the value using the pointer */
    printf("Value of x variable: %d\n", *x);
    return 0;
}
Output:
Address of variable: 61fe14
Address stored in x variable: 61fe14
Value of x variable: 20
NULL Pointers:
  • If we do not have an exact address to be assigned, it’s good to give the NULL value to the pointer variable.
  • This has to be done at the time of declaration of a variable. 
  • A pointer assigned with a NULL value is known as a null
  • It is a constant with zero value.

Array of Pointers:

          Consider the following program,

          Here, x is an array storing integer values, and p is a pointer.

Program:

#include<stdio.h>
const int a=4;
int main()
{
   int x[] = {1,10,20,30};
   int i, *p[a];
   for(i=0;i<a;i++)
   {
       p[i] = &x[i];
       printf("Value of x[%d] = %d\n", i, *p[i]);
   }
   return 0;
}
Output:
Value of x[0] = 1
Value of x[1] = 10
Value of x[2] = 20
Value of x[3] = 30
 Functions
  • In C, Functions are the building blocks, and it is a place where all program activities occur. 

          Syntax:

                          return-type function-name(parameter list)

                        { 

                          body of the function

                        } 

  • The return type defines the type of data returns by a function. A function may give any kind of data except an array. 
  • The parameter list is enclosed in () is a comma-separated list of variable names with their associated types.
  • The parameters receive the argument values at the time of the function call.
  • A function can be without parameters, in that the parameter list enclosed in () is empty.
  • We can explicitly specify the empty parameter list by placing the keyword void inside the parentheses. 

 Scope of a Function 

  • The scope rules are the rules which show the access details. 
  • Each function is defined as a discrete block of code. Therefore, a function defines a block as its scope.
  • This means that the function’s code within its {} is private, and it cannot be accessed by any other statement or a function except through a call to that particular function.
  • The code present within the block of function is hidden from the rest of the program unless it uses global variables. i.e., the code and data defined within one function cannot interact with the code or data defined in another function because every function has different scopes.
  • Variables that are defined within a scope of function are called local variables.
  • A local variable exists when the function is entered, and it is destroyed upon the exit of a function. Therefore, a local variable cannot hold its value between the function calls. 
  • The only exception to this particular rule is when the local variable is declared and the static storage class specifier. 
  • Because this causes the compiler to treat the variable as a global variable for storage but limit its scope to the function. 
  • The formal parameters to a function also fall within the scope of a function. Therefore, a parameter is known throughout the entire function. A parameter comes into existence at the time of the function call and is destroyed at the exit.
  • All functions also have file scope. Thus, we cannot define a function within a function. This is the reason why C is not technically a block-structured language.

Advantages of using functions:

  •  we can avoid rewriting the same logic repeatedly in a program.
  • We can easily debug the extensive C program when it is divided into functions.
  • We can directly call C functions as many times we want and from anywhere in a program.
  • We can easily reuse C functions.

Program:

#include<stdio.h>
int sum(int, int);
int main()
{
    int a,b,c;
    printf("\nEnter first number:");
    scanf("%d",&a);
    printf("\nEnter second number:");
    scanf("%d",&b);
    c = sum(a,b);
    printf("\nThe sum is: %d", c);
}
    int sum(int a, int b)
{
    return a+b;
}
Output:
Enter first number:2
Enter second number:5
The sum is: 7

Who is the course for?

Prerequisites before starting this course:

Questions 🙵 Answers.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent eu orci faucibus orci malesuada semper eget non tellus. Cras sed dignissim purus. Mauris varius neque leo, eu pellentesque justo venenatis et. Sed ultricies risus non turpis tempus, nec  nulla suscipit. In comdo urna eu turpis accumsan, et viverra mauris fringillaCras interdum 

Video 48 Min  + 2 Min read to complete

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent eu orci faucibus orci malesuada semper eget non tellus. Cras sed dignissim purus. Mauris varius neque leo, eu pellentesque justo venenatis et. Sed ultricies risus non turpis tempus, nec  nulla suscipit. In comdo urna eu turpis accumsan, et viverra mauris fringillaCras interdum 

Video 48 Min  + 2 Min read to complete

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent eu orci faucibus orci malesuada semper eget non tellus. Cras sed dignissim purus. Mauris varius neque leo, eu pellentesque justo venenatis et. Sed ultricies risus non turpis tempus, nec  nulla suscipit. In comdo urna eu turpis accumsan, et viverra mauris fringillaCras interdum 

Video 48 Min  + 2 Min read to complete

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent eu orci faucibus orci malesuada semper eget non tellus. Cras sed dignissim purus. Mauris varius neque leo, eu pellentesque justo venenatis et. Sed ultricies risus non turpis tempus, nec  nulla suscipit. In comdo urna eu turpis accumsan, et viverra mauris fringillaCras interdum 

Video 48 Min  + 2 Min read to complete

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent eu orci faucibus orci malesuada semper eget non tellus. Cras sed dignissim purus. Mauris varius neque leo, eu pellentesque justo venenatis et. Sed ultricies risus non turpis tempus, nec  nulla suscipit. In comdo urna eu turpis accumsan, et viverra mauris fringillaCras interdum 

Video 48 Min  + 2 Min read to complete

More Courses

You might also be interested in these courses