Tuesday, January 30, 2024

Arrays - One Dimensional - DSTC using C Language (Source Code Implemented)

Arrays - One Dimensional 
Implemented using C Language

 

Arrays have 2 basic operations i.e. extraction and storing values.

  • Extraction operation is a function that accepts an array (arr) and an index or subscript number ( i ) , and returns a values stored at index nuber. It is denoted as arr[i].

  • Storing operation accepts an array (arr), and index or subscript ( i ), and a value to be stored ( X ). It is denoted as arr[i] = X. Before a value has been assigned to an element of the array, its value is undefined and a reference to it in an expression is illegal.

C Language Code:

       ARRAY1D.H      

#include "assert.h"
typedef struct integer_array
{
int *bfr ;
int size;
}intarr ;

intarr *makearray(int n)
{
intarr *a1;
a1 = (intarr *) malloc(sizeof(intarr)) ;
a1->size = n ;
a1->bfr = (int *) malloc(sizeof(int)*n);
return (a1);
}

void input(intarr *a1,int val, int pos)
{
assert(pos>=0 && pos<a1->size);
assert(val != 0) ;
a1->bfr[pos] = val;
// or *(a1->bfr+pos) = v ;
}

int get(intarr *a1,int pos)
{
assert(pos>=0 && pos<a1->size);
return(a1->bfr[pos]);
// or return(*(a->bfr+pos));
}

void printarray(intarr *a1,int posupto)
{
// if posupto is zero(0) then it will all array elements otherwise
// only the speicified no. of elements.
int i=0,k ;
if (posupto==0)
i=a1->size ;
else
i = posupto ;

//DISPLAYS THE ARRAY BEFORE SORTING
printf("\n");
for(k=0;k<i;k++)
printf("a[%d]\t",k);

printf("\n");
for(k=0;k<i;k++)
printf("%d\t",a1->bfr[k]);
}

void sortarray(intarr *a1)
{
int i=0,j=0,t ;

for(i=0;i<a1->size-1;+i++)
{
for(j=i+1;j<a1->size;j++)
{
if ( a1->bfr[i] > a1->bfr[j] )
{
t = a1->bfr[i];
a1->bfr[i] = a1->bfr[j] ;
a1->bfr[j] = t ;
}
}
}

}

             ARRAY1D.CPP         

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <assert.h>
#include "array1d.h"

void main()
{
intarr *a1;
int i,val,n ;
printf("\n Enter the no.of elements in the array: ");
scanf("%d",&n);
printf("\nvalue entered wwas %d",n);
a1 = makearray(n);
printf("\nsize of array %d",a1->size);
for(i=0;i<n;i++)
{
printf("\n Enter values of a[%d]=",i);
scanf("%d",&val);
// a1->bfr[i] = val ;
input(a1,val,i);
}
printarray(a1,0) ;

sortarray(a1) ;
printarray(a1,0);
}


No comments: