knapz
// Online C compiler to run C program online
#include <stdio.h>
int knapsack(float weight[20],float profit[20],int n,float capacity)
{
float x[20],tp=0;
int i,j,u;
u=capacity;
for(i=0;i<n;i++)
x[i]=0.0;
for(i=0;i<n;i++){
if(weight[i]>u)
break;
else{
x[i]=1;
tp=tp+profit[i];
u=u-weight[i];
}
if(i<n)
x[i]=u/weight[i];
tp=tp+(x[i]*profit[i]);
printf("the resultant vector is :");
for(i=0;i<n;i++){
printf("%d/t/t",x[i]);
}
printf("the max profit is %d",tp);
}
}
int main() {
float weight[20],profit[20],ratio[20],capacity;
int i,j,n,temp;
printf("enter the no. of object");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("enter the weight and profit of the objects %d\n ",i);
scanf("%f %f",&weight[i],&profit[i]);
}
printf("enter the capacity of knapsack %f ");
scanf("%f ",&capacity);
for(i=0;i<n;i++){
ratio[i]=profit[i]/weight[i];
}
for(i=0;i<n;i++){
for(j=i+1;j<n;j++){
if (ratio[i]<ratio[j])
temp=ratio[j];
ratio[j]=ratio[i];
ratio[i]=temp;
temp=weight[j];
weight[j]=weight[i];
weight[i]=temp;
temp=profit[j];
profit[j]=profit[i];
profit[i]=temp;
}}
knapsack(weight,profit,n,capacity);
}