Array in C

Arrays

In C language, arrays are reffered to as structured data types. An arrary is defined as finite ordered collection of homogenous data, stored in contiguous memory locations.
Here the words,
  • finite means data range must be defined.
  • ordered means data must be stored in continuous memory addresses.
  • homogenous means data must be of similar data type.
Example where arrays are used,
  • to store list of Employee or Student names,
  • to store marks of a students,
  • or to store list of numbers or characters etc.
Since arrays provide an easy way to represent data, it is classified amongst the data structures in C. Other data structures in c are structure, lists, queues and trees. Array can be used to represent not only simple list of data but also table of data in two or three dimensions.

Declaring an Array

Like any other variable, arrays must be declared before they are used. General form of array declaration is,
data-type variable-name[size];

for example : 
 
int arr[10];
array declaraction in c
Here int is the data type, arr is the name of the array and 10 is the size of array. It means array arr can only contain 10 elements of int type. Index of an array starts from 0 to size-1 i.e first element of arr array will be stored at arr[0] address and last element will occupy arr[9].

Initialization of an Array

After an array is declared it must be initialized. Otherwise, it will contain garbage value(any random value). An array can be initialized at either compile time or at runtime.

Compile time Array initialization

Compile time initializtion of array elements is same as ordinary variable initialization. The general form of initialization of array is,
type array-name[size] = { list of values };

int marks[4]={ 67, 87, 56, 77 };   //integer array initialization

float area[5]={ 23.4, 6.8, 5.5 };   //float array initialization

int marks[4]={ 67, 87, 56, 77, 59 };    //Compile time error
One important things to remember is that when you will give more initializer than declared array size than the compiler will give an error.
#include< stdio.h>
#include< conio.h>
void main()
{
 int i;
 int arr[]={2,3,4};    //Compile time array initialization
 for(i=0 ; i<3 ; i++)
   printf("%d\t",arr[i]);
 getch();
}
Output
2  3  4

Runtime Array initialization

An array can also be initialized at runtime using scanf() function. This approach is usually used for initializing large array, or to initialize array with user specified values. Example,
#include< stdio.h>
#include< conio.h>
void main()
{
 int arr[4];
 int i,j;
 printf("Enter array element");
 for(i=0;i<4;i++)
 {
  scanf("%d",&arr[i]);    //Run time array initialization
 }
 for(j=0;j<4;j++)
 {
  printf("%d\n",arr[j]);
 }
 getch();
}

Two dimensional Arrays

C language supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array.
Two-dimensional array is declared as follows,
type array-name[row-size][column-size] 

Example : 
int a[3][4];
two dimensional array in c
The above array can also be declared and initialized together. Such as,
int arr[][3] = {
          {0,0,0},
          {1,1,1}
               }; 

Run-time initialization of two dimensional Array

#include< stdio.h>
#include< conio.h>
void main()
{
 int arr[3][4];
 int i,j,k;
 printf("Enter array element");
 for(i=0;i<3;i++)
 {
  for(j=0;j<4;j++)
  {
   scanf("%d",&arr[i][j]);
  }
 }
 for(i=0;i<3;i++)
 {
  for(j=0;j<4;j++)
  {
   printf("%d",arr[i][j]);
  }
 }
getch();
} 
 

string and Character array

string is a sequence of characters that is treated as a single data item and terminated by null character '\0'. Remember that C language does not support strings as a data type. A string is actually one-dimensional array of characters in C language. These are often used to create meaningful and readable programs.
For example : The string "hello world" contains 12 characters including '\0' character which is automatically added by the compiler at the end of the string.

Declaring and Initializing a string variables

There are different ways to initialize a character array variable.
char name[10]="StudyTonight"; //valid character array initialization char name[10]={'L','e','s','s','o','n','s','\0'}; //valid initialization Remember that when you initialize a character array by listings all its characters separately then you must supply the '\0' character explicitly.
Some examples of illegal initialization of character array are,
char ch[3]="hell"; //Illegal char str[4]; str="hell"; //Illegal

String Input and Output

Input function scanf() can be used with %s format specifier to read a string input from the terminal. But there is one problem with scanf() function, it terminates its input on first white space it encounters. Therefore if you try to read an input string "Hello World" using scanf() function, it will only read Hello and terminate after encountering white spaces.
However, C supports a format specification known as the edit set conversion code %[..] that can be used to read a line containing a variety of characters, including white spaces.
#include< stdio.h> #include< conio.h> #include void main() { char str[20]; clrscr(); printf("Enter a string"); scanf("%[^\n]",&str); printf("%s",str); getch(); } Another method to read character string with white spaces from terminal is gets() function.
char text[20]; gets(text); printf("%s",text);

String Handling Functions

C language supports a large number of string handling functions that can be used to carry out many of the string manipulations. These functions are packaged in string.h library. Hence, you must include string.h header file in your program to use these functions.
The following are the most commonly used string handling functions.

MethodDescription
strcat()It is used to concatenate(combine) two string
strlen()It is used to show length of a string
strrev()It is used to show reverse of a string
strcpy()Copies one string into another
strcmp()It is used to compare two string

strcat() function

strcat("hello","world"); strcat() function will add the string "world" to "hello".

strlen() function

strlen() function will return the length of the string passed to it.
int j; j=strlen("studytonight"); printf("%d",j); output : 12

strcmp() function

strcmp() function will return the ASCII difference between first unmatching character of two strings.
int j; j=strcmp("study","tonight"); printf("%d",j); output: -1
 

No comments:

Post a Comment

Thank for your feedback.