Sort the Array in an Ascending Order
#include
#include
void main()
{
int i, j, a, n, number[30];
clrscr();
printf("Enter the value of N \n");
scanf("%d", &n);
printf("Enter the numbers \n");
for (i = 0; i < n; ++i)
scanf("%d", &number[i]);
for (i = 0; i < n; ++i)
{
for (j = i + 1; j < n; ++j)
{
if (number[i] > number[j])
{
a = number[i];
number[i] = number[j];
number[j] = a;
}
}
}
printf("The numbers arranged in ascending order are given below \n");
for (i = 0; i < n; ++i)
printf("%d\n", number[i]);
getch();
}
Output
Enter the value of N
6
Enter the numbers
3
78
90
456
780
200
The numbers arranged in ascending order are given below
3
78
90
200
456
780
Sort the N Names in an Alphabetical Order
#include
#include
#include
void main()
{
char name[10][8], tname[10][8], temp[8];
int i, j, n;
clrscr();
printf("Enter the value of n \n");
scanf("%d", &n);
printf("Enter %d names n", \n);
for (i = 0; i < n; i++)
{
scanf("%s", name[i]);
strcpy(tname[i], name[i]);
}
for (i = 0; i < n - 1 ; i++)
{
for (j = i + 1; j < n; j++)
{
if (strcmp(name[i], name[j]) > 0)
{
strcpy(temp, name[i]);
strcpy(name[i], name[j]);
strcpy(name[j], temp);
}
}
}
printf("\n----------------------------------------\n");
printf("Input NamestSorted names\n");
printf("------------------------------------------\n");
for (i = 0; i < n; i++)
{
printf("%s\t\t%s\n", tname[i], name[i]);
}
printf("------------------------------------------\n");
getch();
}
Output
Enter the value of n
7
Enter 7 names
heap
stack
queue
object
class
program
project
----------------------------------------
Input Names Sorted names
------------------------------------------
heap class
stack heap
queue object
object program
class project
program queue
project stack
------------------------------------------
Read an Array and Search for an Element
#include
#include
void main()
{
int array[20];
int i, low, mid, high, key, size;
clrscr();
printf("Enter the size of an array\n");
scanf("%d", &size);
printf("Enter the array elements\n");
for (i = 0; i < size; i++)
{
scanf("%d", &array[i]);
}
printf("Enter the key\n");
scanf("%d", &key);
low = 0;
high = (size - 1);
while (low <= high)
{
mid = (low + high) / 2;
if (key == array[mid])
{
printf("Successful search\n");
return;
}
if (key < array[mid])
high = mid - 1;
else
low = mid + 1;
}
printf("Unsuccessful search\n");
getch();
}
Output
Enter the size of an array
4
Enter the array elements
90
560
300
390
Enter the key
90
Successful search
Enter the size of an array
4
Enter the array elements
100
500
580
470
Enter the key
300
Unsuccessful search
No comments:
Post a Comment