In: Computer Science
#include <stdio.h>
void printDistinct(int arr[], int c)
{
int i, j;
printf("\nArray:\n");
// Picking all elements one by one
for (i = 0; i < c; i++)
{
// Checking if the picked element is already printed
for (j = 0; j <= i; j++)
{
// If current element is already there in the array, break from j
loop
if (arr[i] == arr[j])
{
break;
}
}
// If it is not printed earlier and is within 10-100, then we print
it
if (i == j && arr[i] > 10 && arr[i] <
100)
printf("%d ", arr[i]);
}
}
int main()
{
// to test above function
int arr[20], i;
printf("Enter 20 numbers between 10-100\n");
for (i = 0; i < 20; i++)
{
scanf("%d", &arr[i]);
}
int c = sizeof(arr) / sizeof(arr[0]);
printDistinct(arr, c);
int a[20], j, k, t, n = 20;
//-------------------------------------------------------------------------------------
for (i = 0; i < n; i++) //Sort array in ascending order
{
for (j = i + 1; j < n; j++)
{
if (a[j] < a[i]) //Check jth element smaller than ith
element
{
t = a[i]; //if yes,assign the ith value to a temporary
variable
a[i] = a[j]; //Assign the value of jth element to i.
a[j] = t; //Then assign value of temporary variable to j.
}
}
}
printf("\nSorted array is: "); //Finally print sorted array
for (i = 0; i < n; i++)
{
printf("%d ", a[i]);
}
return 0;
}
and the output for sorted is this
-858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460
what i need to do to make sure that the numbers are sorted properly.
Please find the updated code and output below.
#include <stdio.h>
void printDistinct(int arr[], int c)
{
int i, j;
printf("\nArray:\n");
// Picking all elements one by one
for (i = 0; i < c; i++)
{
// Checking if the picked element is already printed
for (j = 0; j <= i; j++)
{
// If current element is already there in the array, break from j
loop
if (arr[i] == arr[j])
{
break;
}
}
// If it is not printed earlier and is within 10-100, then we print
it
if (i==j && arr[i] > 10 && arr[i] <
100){
printf("%d ", arr[i]);
}
}
}
int main()
{
// to test above function
int arr[20], i;
printf("Enter 20 numbers between 10-100\n");
for (i = 0; i < 20; i++)
{
scanf("%d", &arr[i]);
}
int c = sizeof(arr) / sizeof(arr[0]);
printDistinct(arr, c);
int j, k, t, n = 20;
//-------------------------------------------------------------------------------------
for (i = 0; i < n; i++) //Sort array in ascending order
{
for (j = i + 1; j < n; j++)
{
if (arr[i] > arr[j]) //Check jth element smaller than ith
element
{
t = arr[i]; //if yes,assign the ith value to a temporary
variable
arr[i] = arr[j]; //Assign the value of jth element to i.
arr[j] = t; //Then assign value of temporary variable to j.
}
}
}
printf("\nSorted array is: "); //Finally print sorted array
for (i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
return 0;
}
OUTPUT :