Programs Related To 1D Arrays
Programs Related To 1D Arrays
}
Write a program to display the largest and smallest element from the group
of 1D array elements
#include<stdio.h>
int main()
{
int n,a[10],i,max,min;
printf("\n Enter number of elements:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
min=a[0];
for(i=1;i<n;i++)
{
if(a[i]<min)
{
min=a[i];
}
}
max=a[0];
for(i=1;i<n;i++)
{
if(a[i]>max)
{
max=a[i];
}
}
printf("\nMaximum element is: %d",max);
printf("\nMinimum element is: %d",min);
return 0;
}
Write a program to implement linear search in 1D array
#include <stdio.h>
int main()
{
int a[50];
int i, loc = -1, key,n;
printf("\n Enter value of n:");
scanf("%d",&n);
printf("\n Enter the elements:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Enter integer value to search in array:");
scanf( "%d", &key );
// attempt to locate searchKey in array a
for ( i = 0; i < n; i++ )
{
if ( a[i] == key )
{
loc = i; // location of key is stored
break;
} // end if
} // end for
if(loc!= -1)
{
printf("Element found at %d",loc+1);
}
else
{
printf("Element not found");
}
} // end main
Write a program to implement binary search in 1D array
#include<stdio.h>
int main()
{
for (j=0;j<n-i-1;j++)
{
// compare adjacent elements and swap them if first
// element is greater than second element
if (a[j]>a[j+1])
{
hold=a[j];
a[j]=a[j+1];
a[j+1]=hold;
} // end if
} // end inner for
} // end outer for
printf( "\nData items in ascending order" );
for (i=0;i<n;i++)
{
printf("%d ",a[i]);
} // end for
} // end main
Dry running (Bubble sort)
Write a program insert an element at a given position in 1D array
#include <stdio.h>
int main()
{
int array[100], position, c, n, value;
printf("Enter number of elements in array:\n");
scanf("%d", &n);
printf("Enter %d elements:\n", n);
for (c = 0; c < n; c++)
{
scanf("%d", &array[c]);
}
printf("Enter the location where you wish to insert an element:\n");
scanf("%d", &position);
printf("Enter the value to insert:\n");
scanf("%d", &value);
scanf("%d", &position);
for (c = position-1; c < n-1; c++)
{
array[c] = array[c+1];
}