Wednesday, 8 January 2014

C Programming Language Tutorial XII – Array (Single Dimensional)

Array
- A set of elements of similar data type is an array.
- A collection of data elements that are of same type.
Why array is need?
Till now in program we have seen variables which can store only one value at a time. But it is often required in programming that may need to store set of values in one variable. In such case we can create and use array.
Advantage
§ We can easily create set of similar type of data.
§ All elements allocate sequential memory.
§ Sorting and searching processes become fast.
One Dimensional Array
Declaring an array
Data-type variable name[size];
Memory Representation
All elements of the array gets store in consecutive memory locations.
e.g. int x[5];                    



                                                           600     602    604     606     608

Referring Elements of An Array
Main thing about array is how to access the individual element from it.
You can access or refer to the individual element of an array through their position or location in the array. The position and location of an array is commonly referred as array subscript. An arrays subscript always starts from 0.
                                                            x[0]     x[1]    x[2]    x[3]    x[4]
How to initialize or store values
We can initialize array at a time of declaration.
int arr[5] = {12, 23, 34, 45, 56};
x[0]=12; x[1]=23; x[2]=34; x[3]=45; x[4]=56;
Let us simplify this concept by taking a simple example of “program to print sum of 1 to 10 values”.
Normal Approach
Array Approach
Requires 10 variables
e.g. – int n1,n2,n3,……..,n10;
Requires 10 variables
               e.g. – int num[10];
Scan for 10 times
e.g. – scanf(“%d%d….%d’,&n1,&n2,&n3……,&n10);
Scan for 1 times
e.g. – for(i=0;i<10;i++)
          scanf(“%d”,&num[i]);
sum = n1+n2+n3+……………….+n10;
for(i=0;i<10;i++)
    sum = sum + x[i];
Random memory allocation
Sequential memory allocation
Sorting and searching become complicated and time consuming processes.
Sorting and searching become easy.
Let us create this example but before that let us create a simple program to scan and print elements of array with their positions.
//prog to scan and print all elements of array
#include<stdio.h>
#include<conio.h>
void main()
{
 int x[10],i;       
clrscr();
 printf("\nEnter 10 elements of x array:\n");
 for(i=0;i<10;i++)
 {
  scanf("%d",&x[i]);      //scan elements of array from 0 till 9
 }
 printf(“\nElements of array: “);
 for(i=0;i<10;i++)
 {
    printf(“\nx[%d] = %d”,i,x[i]);   //x[%d] will prints position and %d shows value at currnt position
 }
getch();
}
Enter 10 elements of x array:
12
21
34
42
57
61
73
82
90
10
Elements of array:
x[0]=12
x[1]=21
x[2]=34
x[3]=42
x[4]=57
x[5]=61
x[6]=73
x[7]=82
x[8]=90
x[9]=10
//prog to print sum & average of all elements of array
#include<stdio.h>
#include<conio.h>
void main()
{
 int x[10],i,sum=0;         //sum will use on left and right side so initialized it to zero
 float avg;
 clrscr();
 printf("\nEnter 10 elements of x array:\n");
 for(i=0;i<10;i++)
 {
  scanf("%d",&x[i]);      //scan elements of array from 0 till 9
 }
 for(i=0;i<10;i++)
 {
  sum = sum + x[i];       //add one by one element
 }
 avg = (float)sum/10;   //sum is temporarily converted to float fro accurate result (type casting)  
 printf("\nSum of all elements of array = %d",sum);
 printf("\nAverage of all elements of array = %.2f",avg);
 getch();
}
Enter 10 elements of x array:
1
2
3
4
5
6
7
8
9
10
Sum of all elements of array = 55
Average of all elements of array = 5.5
//program to search element and print whether it is present or not.
#include<stdio.h>
#include<conio.h>
void main()
{
 int x[10],i,no,flag;
 clrscr();
 printf("\nEnter 10 elements of x array:\n");
 for(i=0;i<10;i++)
 {
  scanf("%d",&x[i]);
 }
 printf("Enter any number for searching: ");
 scanf("%d",&no);
 for(i=0;i<10;i++)
 {
   if(x[i] == no)      
   {
    flag=1;           //set to 1 if number is present
    printf("\nNumber is present in array at x[%d] position",i);
    break;           //to get exit from loop if number is found then no need to check further numbers
   }
   else
    flag=0;         //set to 0 if number is not present 
   }
   if(flag==0)   //every time this condition is checked
     printf("Number is not present in array\n");
 getch();
}
o/p:
Enter 10 elements of x array:
1
2
3
4
5
6
7
8
9
10
Enter any number for searching: 7
Number is present in array at x[6] position
Assignments:
1.     Create a program to print sum of all even numbers presented in array //by if statement check whether the number is even or not. If it is even then add it to even sum
2.     Create a program to print sum of all odd numbers presented in array //apply logic as above
3.     Create a program to accept 10 elements of array and print incrementing by 10.
e.g. x – 1          2          3          4          5
output will be : x – 11    12         13         14         15    
//program to print sum & average of all elements of array
#include<stdio.h>
#include<conio.h>
void main()
{
 int x[10],y[10],i;
 clrscr();
 printf("\nEnter 10 elements of x array: \n");
 for(i=0;i<10;i++)
 {
  scanf("%d",&x[i]);
 }
 for(i=0;i<10;i++)
 {
   y[i] = x[i];    //copy one by one element from x to y array
 }
 printf("\nCopied elements of array: \n");
 for(i=0;i<10;i++)
 {
  printf("%d\t",y[i]);
 }
 getch();
}
o/p:
Enter 10 elements of x array:
1
2
3
4
5
6
7
8
9
10
Copied elements of array:
1        2      3      4      5      6     7      8     9     10
Assignment:
1.     Create a program to copy elements of array in reverse order.
e.g. x – 1          2          3          4          5
output will be : y – 5      4          3          2          1    
In above programs we have used fixed sized array. Now we will use array with user defined size. How to declare it?
int  x[50]; - declared array with maximum size.
Scan size of array by user-
printf(“\nEnter size for array: ”);
scanf(“%d”,&n);
Now you are ready to scan elements of array up to n size as follows
for(i=0;i<n;i++)
{
   scanf(“%d”,&x[i]);
}
//Program to merge elements of array by user define size
#include<stdio.h>
#include<conio.h>
void main()
{
  int x[50],y[50],z[100];    //elements of x and y array combined in z array
  int i,k=0,n,m;
  clrscr();
 
  printf("\nEnter size of x & y array respectively: ");
  scanf("%d%d",&n,&m);
  printf("\nEnter %d elements of x array: \n",n);
  for(i=0;i<n;i++)
  {
     scanf("%d",&x[i]);
   }
  printf("\nEnter %d elements of y array:\n",m);
  for(i=0;i<m;i++)
  {
     scanf("%d",&y[i]);
   }
  //process
    for(i=0;i<n;i++)
    {
        z[k] = x[i];      //copy the elements of x to z array. K is used for accessing index of z. k is initially assign to zero because every array index starts from zero
        k++;
     }
    for(i=0;i<m;i++)
    {
        z[k] = y[i];   //copy the elements of y to z array from kth position
        k++;
     }
      printf("\nMerged elements of array:\n");
      for(i=0;i<k;i++)
      {
        printf("%d\t",z[i]);
      }
      getch();
}
o/p:
Enter size of x & y array respectively: 5 4
Enter 5 elements of x array:
1
2
3
4
5
Enter 4 elements of y array:
4
3
2
1
Merged elements of array:
1    2    3    4    5    4    3    2    1
---------x-----------    ---------y-------
In C ProgrammingLanguage Tutorial XI chapter you have studied function call by value.  
Now let us start with function call by reference.
Function call by reference
Changes made in function are directly reflected into main() program. In this case, instead of variables, it’s address is passed as an argument from main() to function. Any changes made in formal argument in function part are directly get reflected back into main() program. This type of function is used in case of array, structure and pointer
Changes are directly gets reflected to one another therefore no need to return any value. Hence you can use simply void as return type.
How to pass array to function:
Prototype function – returntype function(datatype []); 
Function calling     -  function(arrayvariable);
Function definition – returntype function(datatype array[])
//Addition of array with function
#include<stdio.h>
#include<conio.h>
void getarr(int []);                   //single array is pass for scanning elements you can call this function for two arrays by passing single array
void addarr(int [],int [],int []);  //three array are pass for addition of elements of 1st and 2nd array into 3rd array
void showarr(int []);               //single array is pass for printing elements. You can call such function by passing one by one array. This avoids repetition.
int i,n; //global variable          //n is taken for size of all array because while performing addition all array should have same size.
void main()
{
  int x[50],y[50],z[50];
  clrscr();
 printf("\nEnter size of array: ");
 scanf("%d",&n);
printf("\nEnter elements of x array\n");
getarr(x);                                  //getarr function is called for x array
printf("\nEnter elements of y array\n");
getarr(y);                                  //getarr function is called for y array
addarr(x,y,z);        //addarr function is called            
printf("\nAddition of array\n");
showarr(z);          //showarr function is called for resultant array
getch();
}
//function definition section
void getarr(int x[])
{
  for(i=0;i<n;i++)
  {
    scanf("%d",&x[i]);
  }
}
void addarr(int x[],int y[],int z[])
{
 for(i=0;i<n;i++)
 {
   z[i] = x[i] + y[i];
 }
}
 
void showarr(int z[])
{
 for(i=0;i<n;i++)
  {
    printf("%d\t",z[i]);
  }
}
Enter size of array: 7
Enter elements of x array
1   2   4   5   6   7
Enter elements of y array
1   2   4   5   6   7
Addition of array
2   4   8   10   12   14
Assignment: Convert above programs (before addition of array) of array to function.
//prog to print biggest & smallest element from array
#include<stdio.h>
#include<conio.h>
void main()
{
  int x[100],i,j,n,temp;
  clrscr();
  printf("\nEnter size of x array: ");
  scanf("%d",&n);
  printf("\nEnter %d elements of x array\n",n);
  for(i=0;i<n;i++)
  {
     scanf("%d",&x[i]);
  }
  //process
  for(i=0;i<n;i++)
  {
      for(j=i+1;j<n;j++)
     {
        if(x[i] > x[j])        //compare element from location x[i] to x[j]. if x[i] is greater than x[j] then only                                                                                 their values will swap
        {
           temp = x[i];
           x[i] = x[j];
           x[j] = temp;
          }
       }
    }
  printf("\nAfter sorting elements of x array\n");
  for(i=0;i<n;i++)
  {
     printf("%d\t",x[i]);
  }
  printf("\nBiggest value = %d",x[n-1]);
  printf("\nSmallest value = %d",x[0]);
 getch();
}
 //you can notice that here only single array has scanned, processed and printed  
o/p:
Enter size of x array: 10
Enter 10 elements of x array
7
2
5
8
1
3
6
4
9
1
After sorting elements of x array
1   1   2   3   4   5   6   7   8   9 
Biggest value = 9
Smallest value = 1
Next program is of intersection of array. Intersection means only common elements from two arrays will store in resultant array. Here this program will create by using function. You can try it without function.
//Intersection of array with function
#include<stdio.h>
#include<conio.h>
void getarr(int [],int);
void intersect(int [],int [],int [],int,int);   //last two integers are passed for size of 1st and 2nd array
void showarr(int [],int);
 int i,k=0;    //we do not take here size of 1st and 2nd array as global because it is good programming habit of taking minimum global variables.
void main()
{
  int x[50],y[50],z[50];
  int n,m;
 clrscr();
 printf("Enter size of x & y array\n");
 scanf("%d%d",&n,&m);
 printf("Enter %d ele of x array\n",n);
  getarr(x,n);
  printf("Enter %d ele of y array\n",m);
  getarr(y,m);
  intersect(x,y,z,n,m);
  showarr(z,k);
  getch();
}
void getarr(int x[],int n)
 {
   for(i=0;i<n;i++)
   {
      scanf("%d",&x[i]);
    }
}
void showarr(int z[],int k)
 {
    printf("Intersection of array\n");
   for(i=0;i<k;i++)
   {
      printf("%d\t",z[i]);
    }
}
void intersect(int x[],int y[],int z[],int n,int m)
 {
   int j;
   for(i=0;i<n;i++)
   {
     for(j=0;j<m;j++)
     {
       if(x[i] == y[j])  //check whether value of x = y. If it is yes then only store in z
       {
          z[k] = x[i];
          k++;
        }
      }
     }
   }

No comments:

Post a Comment