Showing posts with label Arrays in C. Show all posts
Showing posts with label Arrays in C. Show all posts

Thursday, 7 March 2019

Multi-Dimensional Array in C (Part 3)

In C, arrays can have more than one subscript. Arrays having more than one subscript are known as multi-dimensional arrays.
Multi-dimensional array is an array of array or more precisely collection of array.
So Two-dimensional array is the collection of one-dimensional array, Three-dimensional array is collection of two-dimensional array and so on.

In this tutorial, you will study two-dimensional arrays.
Two-dimensional array is a collection of one-dimensional array. They are logically represented a matrix. Any matrix problem can be converted easily to a two-dimensional array.

Declaring 2-D array
  • Like a variable, we must declare an array before using it.
  • Declaring an array tells the compiler the kind of values an array will hold, number of rows and columns,
  • The general syntax for declaring an array is as follows:

                       data_type   array_name[rows][columns];
   Examples:
int arr[3][4];               // array marks holds 10 integer values

Initializing 2-D Array
Initializing a two-dimensional array is similar to a one-dimensional array  with one difference. Difference is that you put the initial values for each row between braces, {}, and then enclose all the rows between braces.
Syntax
   array_name[row][columns]={
   {val1,val2…},{ val1,val2…},{ val1,val2…}..
};

Example:
int arr[3][4] = {
{ 11, 12, 13, 14 }, // Values for first row
{ 21, 22, 23, 24 }, // Values for second row
{ 31, 32, 33, 34 } // Values for third row
};
Each set of values that initializes the elements in a row is between braces, and the whole lot goes between another pair of braces. The values for a row are separated by commas, and each set of row values is separated from the next set by a comma.
If you specify fewer initializing values than there are elements in a row, the values will be assigned to row elements in sequence, starting with the first. The remaining elements in a row that are left when the initial values have all been assigned will be initialized to 0. You can initialize the whole array to 0 by supplying just one value:
int arr[3][4] = {0};

It is important to remember that while initializing a 2-D array it is necessary to mention the second (column) dimension, whereas the first dimension (row) is optional. Thus the declarations,
int arr[2][3] = { 11, 12, 13, 14, 15, 16 } ;
int arr[ ][3] = { 11, 12, 13, 14, 15, 16 } ;
are perfectly acceptable,
whereas,
int arr[2][ ] = { 11, 12, 13, 14, 15, 16 } ;
int arr[ ][ ] = { 11, 12, 13, 14, 15, 16 } ;
are invalid.

Entering data into 2-D array
Two nested loops are needed for entering data into a 2-D array.
Syntax:
int i,j;
for(i=0;i<rows;i++){
  for(j=0;j<columns:j++){
    scanf(“%d”,&arr[i][j]);
  }
}

Accessing elements of 2-D array
You need a nested loop to process all the elements in a multidimensional array. The level of nesting will be the number of array dimensions. Here’s how you could sum the elements in the previous numbers array:
Syntax:
int i,j;
for(i=0;i<rows;i++){
  for(j=0;j<columns:j++){
    printf(“%d\t”,arr[i][j]);
  }
 printf(“\n”);
}
printf("The sum of the values in the numbers array is %d.", sum);
Each loop iterates over one array dimension. For each value of i, the loop controlled by j will execute completely.

//Complete c program to read and write data into 2-D array

#include<stdio.h>
int main()
{
    int arr[3][3];
    int i,j;

    //Entering number into 2D array
    for(i=0; i<3; i++){
            for(j=0; j<3; j++){
        printf("Enter number:");
        scanf("%d",&arr[i][j]);
      }  
    }
    printf("\n");
    //Dislaying elements from 2D array
    printf("Elements of 2D array\n");
    for(i=0; i<3; i++){
            for(j=0; j<3; j++){
        printf("%d\t",arr[i][j]);
      } 
              printf("\n");
    }
    printf("\n");
   
    //Dislaying address of elements of 2D array to show that they are stored in continuous memory locations.
    printf("\nFollowing addresses shows that elements of multi dimensional array are also stored in continuous memory locations.\n");
    for(i=0; i<3; i++){
            for(j=0; j<3; j++){
        printf("%d\t",&arr[i][j]);
      } 
    }
    printf("\n");
    return 0;
}
Output:


Memory representation of a 2-Dimensional Array
Like one-dimensional array, in a two-dimensional array, the array elements are stored in one continuous memory locations.

Please comment if you find anything incorrect, or you want to improve the topic discussed above.

Single-Dimensional Array in C (Part 2)

In the previous tutorial, you learnt following things about arrays:
  1. What are arrays?
  2. Why do we need arrays?
  3. Types of arrays?
  4. Declaration and initialization of 1-D arrays

In this tutorial, you will learn entering values into already declared 1-D array and accessing elements of 1-D array.
Entering input data into an array
Once array is declared, we use for loop for entering data into array. Since array index starts with 0, for loop will start with 0;
Example:
int marks[10];
for(i=0; i<10; i++){
        printf("Enter marks of student %d\n",i+1);
        scanf("%d",&marks[i]);
    }
Reading data from an array
Since we have entered marks into marks array, we will use for loop to display the content of this array:
Example:
for(i=0;i<10;i++){
        printf("Marks of student %d are %d.\n",i+1,marks[i]);
    }
This for loop steps through the elements in the array and outputs each value. You use the loop control variable i to produce the sequence number for the value of the number of the element and to access the corresponding array element.
//Following program asks user for marks, then display them
#include<stdio.h>
int main(){
    int marks[10];
    int i;

    //Entering marks into marks array
    for(i=0; i<10; i++){
        printf("Enter marks of student %d\n",i+1);
        scanf("%d",&marks[i]);
    }
   
    //Dislaying marks from marks array
    for(i=0;i<10;i++){
        printf("Marks of student %d are %d.\n",i+1,marks[i]);
    }
    return 0;
}

Output:

Please comment if you find anything incorrect, or you want to improve the topic discussed above.

Tuesday, 5 March 2019

Single-Dimensional Array in C (Part 1)

What is an array?
  • An array is the collection of elements of single/similar type.
  • These similar elements could be of all ints, all floats, all chars etc.
  • The elements of an array are referred by a single name.
  • All elements of an array must be of same type.

Why do we need arrays?
Suppose we want to store marks of 40 students of a class. There are two options:-
  1. Declare 40 variables to hold marks of 40 students. Or
  2. Declare an array of size 40 to hold marks of 40 students. 

Option 2 is better compared to first one. Because it would be much easier to handle single variable than managing 40 variables.

Types of arrays
  1. Single Dimensional (1 D) array
  2. Multi-Dimensional (n D) array where n=2,3,4…..

Single Dimensional (1 D) Array
Definition
·         Conceptually you can think of a one-dimensional array as a row, where elements are stored one after another.
·         Memory representation of 1-D array:
Declaring 1 D array:
  • Like a variable, we must declare an array before using it.
  • Declaring an array tells the compiler the kind of values an array will hold and its size.
  • The general syntax for declaring an array is as follows
               data_type   array_name[size_of_array];


   Examples:
  • int marks[10];               // array marks holds 10 integer values
  • float salary[5];             //array salary holds 5 real numbers
  • char name[4];           //character array name can hold 4 characters


Initialiazing 1-D array
·         To initialize the elements of an array, you just specify the list of initial values between braces and separate them by commas in the declaration.
Syntax
·         array_name[size]={value1, value 2, value 3,…..};
Example:
  • marks[10]={67,87,89,90,98,65,79,86,45,33};
  • salary[5]={,887.0,689.0,970.0,968.0,695.0};
  •  name[]={‘D’,’E’,’E’,’P’};

Declaration and initiazation
·         Declaration and initialization can be grouped together.
Syntax
·         Data_type array_name[size]={value1, value 2, value 3,…..};
Examples:
·         int marks[10]={67,87,89,90,98,65,79,86,45,33};
·         float salary[5]={,887.0,689.0,970.0,968.0,695.0};
·         char name[]={‘D’,’E’,’E’,’P’};

Accessing array elements:
The elements of an array can be accessed by specifying array name followed by subscript or index inside square brackets (i.e []).
For example, accessing elements of above marks array,
first element=marks[0];
second element=marks[1];
element at ith index=marks[i];
Notes:
  1. Array subscript or index starts at 0.
  2. If the size of an array is n then the first element is at index 0, while the last element is at index n-1.
  3. The first valid subscript (i.e 0) is known as the lower bound, while last valid subscript is known as the upper bound.
  4. The C language doesn’t check bounds of the array. It is the responsibility of the programmer to check array bounds whenever required.
  5. Elements of an array are stored in continuous memory locations.
  6. An array is also known as a subscripted variable.
  7. Before using an array its type and dimension must be declared.
  8. If the array is initialized where it is declared, mentioning the dimension of the array is optional



Please comment if you find anything incorrect, or you want to improve the topic discussed above. 

Thursday, 28 February 2019

Displaying elements of an array in reverse order

 Problem : Displaying the elements of an array in reverse order
  Input :
          Array[5]={10,20,30,40,50};
  Output:
          50,40,30,20,10
/*
C program to display elements in reverse order: program will not change the order in memory.it will simply display in reverse order
*/
#include<stdio.h>
int main(){
    int array[10];
    int i;

    //Entering numbers into  array
    for(i=0; i<10; i++){
        printf("Enter a number\n");
        scanf("%d",&array[i]);
    }
   
    //Reading and Displaying numbers from  array in their original order
    printf("\nArray elements in their original order:\n");
    for(i=0;i<10;i++){
        printf("%d\t",array[i]);
    }

    printf("\nArray elements in reverse order:\n");
    //Reading and Dislaying numbers from  array in reverse order
    for(i=9;i>=0;i--){
        printf("%d\t",array[i]);
    }
    printf("\n");
    return 0;
}

Output:

Please comment if you find anything incorrect, or you want to improve the topic discussed above.

Wednesday, 27 February 2019

Finding number of elements in an array

Problem: Given an array of integers ,find the number of elements in it.
Examples:
       Input : array[]={76,90,87,98,56,77,91}
       Output :
          No of Elements :7
         
//C program to find the number of elements in an array
#include<stdio.h>
    int main(){
       int array[]={76,90,87,98,56,77,91};
       int arraySize=0;

      /*key here is sizeof operator which return the size in byte: sizeof(array) 
       determines the size of array in bytes and sizeof(array[0]) determines of first 
       element in byte.*/

      //finding the size(no of elements) of array
       arraySize = sizeof(array)/ sizeof(array[0]);

       printf("Number of Elements in the array are %d.\n",arraySize);
  return 0;
}
Output:













Please comment if you find anything incorrect, or you want to improve the topic discussed above.

Tuesday, 26 February 2019

C program to find minimum and maximum elements in an array

Problem : Given an array of integers ,find the smallest element in it.
Examples:
       Input : array[]={76,90,87,98,56,77,91}
       Output :
          Maximum : 98
          Minimum : 56
Solution:
   Minimum Element:
  1. We assume that first element of the array is the minimum one.
  2. Then iterate the array and compare each element with the assumed minimum element.
  3. If current element is minimum than assumed minimum element, we update the assumed minimum element to current element. This process continues till all elements are checked.

Maximum Element:
  1. We assume that first element of the array is the maximum one.
  2. Then iterate the array and compare each element with the assumed maximum element.
  3. If current element is larger than assumed largest element, we update the assumed maximum element to current element. This process continues till all elements are checked.


// C program to find the minimum and maximum elements in an array
#include<stdio.h>
    int main(){
       int array[]={76,90,87,98,56,77,91};
       int max,min,arraySize=0,i;
      //finding the size(no of elements) of array
       arraySize = sizeof(array)/ sizeof(int);
       max=array[0];  //assume that first element is the maximum one
       min=array[0];  //assume that first element is the minimum one
       for (i = 1; i < arraySize; i++){             
         if (array[i]>max){
            max=i;
         }
        if (array[i]<min){
            min=i;
         }            
       }
       printf("Maximum Element is %d at position %d.\n",array[max],max);
       printf("Minimum Element is %d at position %d.\n",array[min],min);
 return 0;
}
Output:

Please comment if you find anything incorrect, or you want to improve the topic discussed above.