C PROGRAM TO SORT THE NUMBERS BASED ON THE WEIGHT

ALGORITHM:   

    1. Start 

    2. Declare variables  

    3. Read the number of elements . 

    4. Get the individual elements. 

    5. Calculate the weight  for each element by the conditions   5 if it is a perfect cube (pow)  4 if it is a multiple of 4 and divisible by 6 (modulus operator)  3 if it is a prime number(modulus operator) 

    6. Display the output of the weight calculations after sorting . 

    7. Stop

PROGRAM:

#include <stdio.h>
#include <math.h>
void main()
{
int nArray[50],wArray[50],nelem,i,j,t;
printf("\nEnter the number of elements in an array : ");
scanf("%d",&nelem);
printf("\nEnter %d elements\n",nelem);
for(i=0;i<nelem;i++)
 scanf("%d",&nArray[i]);
 for(i=0; i<nelem; i++)
{
 wArray[i] = 0;
 if(percube(nArray[i]))
 wArray[i] = wArray[i] + 5;
 if(nArray[i]%4==0 && nArray[i]%6==0)
wArray[i] = wArray[i] + 4;
 if(prime(nArray[i]))
 wArray[i] = wArray[i] + 3;
}
// Sorting an array
for(i=0;i<nelem;i++)
 for(j=i+1;j<nelem;j++)
 if(wArray[i] > wArray[j])
 {
t = wArray[i];
wArray[i] = wArray[j];
wArray[j] = t;
 }
for(i=0; i<nelem; i++)
 printf("<%d,%d>\n", nArray[i],wArray[i]);
 getch();
}
int prime(int num)
{
int flag=1,i;
for(i=2;i<=num/2;i++)
 if(num%i==0)
 {
 flag=0;
 break;
 }
 return flag;
}
int percube(int num)
{
 int i,flag=0;
 for(i=2;i<=num/2;i++)
 if((i*i*i)==num)
 {
flag=1;
break;
 }
return flag;
}


OUTPUT:

Enter the number of elements in an array :5
Enter 5 elements:
8
11
216
24
34
<34,0>
<11,3>
<24,4>
<8,5>
<216,9>

Explanation:


8 is a perfect cube of 2, not a prime number and not a multiple of 4 & divisible of 6 so the
answer is 5
11 is a prime number so the answer is 3
216 is a perfect cube and multiple of 4 & divisible by 6 so the answer is 5+4 = 9
24 is not a perfect cube and not a prime number and multiple of 4 & divisible by 6 so the
answer is 4
34 not satisfied all the conditions so the answer is 0

Leave a comment