The document presents a C program to solve the 0-1 knapsack problem using dynamic programming. It includes a function to calculate the maximum value that can be carried in a knapsack based on user-defined item weights and values. The program prompts the user for the number of items, their respective values and weights, and the knapsack's capacity before displaying the maximum achievable value.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
11 views2 pages
Expriment 9 C 69
The document presents a C program to solve the 0-1 knapsack problem using dynamic programming. It includes a function to calculate the maximum value that can be carried in a knapsack based on user-defined item weights and values. The program prompts the user for the number of items, their respective values and weights, and the knapsack's capacity before displaying the maximum achievable value.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2
Experiment: 9
Name: Khiyani Sudhiksha
Roll No: C 69 PRN: 2425010083
Question: Write a program to find the solution for a 0-1 knapsack
problem using dynamic programming.
Code:
#include <stdio.h>
// Function to solve the 0/1 Knapsack problem using dynamic programming
int knapsack(int capacity, int weights[], int values[], int n) { // Create a DP table to store the maximum value for each subproblem int dp[n + 1][capacity + 1];
// Initialize the DP table
for (int i = 0; i <= n; i++) { for (int w = 0; w <= capacity; w++) { if (i == 0 || w == 0) { dp[i][w] = 0; // Base case: no items or no capacity } else if (weights[i - 1] <= w) { // Item can be included, choose the maximum of including or excluding it dp[i][w] = (values[i - 1] + dp[i - 1][w - weights[i - 1]] > dp[i - 1][w]) ? values[i - 1] + dp[i - 1][w - weights[i - 1]] : dp[i - 1][w]; } else { // Item cannot be included, exclude it dp[i][w] = dp[i - 1][w]; } } }
// The value at dp[n][capacity] is the maximum value that can be achieved
return dp[n][capacity]; }
int main() { // Number of items int n; printf("Enter the number of items: "); scanf("%d", &n);
// Arrays to store item values and weights
int values[n], weights[n];
// Input the value and weight of each item
for (int i = 0; i < n; i++) { printf("Enter value and weight for item %d: ", i + 1); scanf("%d %d", &values[i], &weights[i]); }
// Capacity of the knapsack
int capacity; printf("Enter the capacity of the knapsack: "); scanf("%d", &capacity);
// Solve the knapsack problem
int maxValue = knapsack(capacity, weights, values, n);
// Output the maximum value that can be carried in the knapsack
printf("Maximum value that can be carried: %d\n", maxValue);