I have to solve the following problem:
Raghav is an online shopper. He wants to order some products. But before he orders the products he wants to compare it with the other merchants. Each row specifies a product but the limitation of comparing the prices are only with maximum of three merchants. Find the minimum in each row and add the price and display.
Assume the limit to buy a product is 10. Assume the number of merchant for each product may vary from 1 to 3.
Test cases
Input 1
Enter the number of products:
3
Enter the price per product:
110 102 100
250 200 312
412 450 475
Output 1
The minimum cost of each product is as follows
100
200
412
Total amount you need to pay Rs.712
Input 2
Enter the number of products:
13
Output 2
You are allowed to buy maximum of 10 products
Input 3
Enter the number of products:
3
Enter the price per product
100 250
500 300
450 350
Output 3
The minimum cost of each product is as follows
100
300
350
Total amount you need to pay Rs.750
This is my code:
#include<stdio.h>
#include<stdlib.h>
#define NN 31
int main()
{
int n;
printf("Enter the number of products:\n");
scanf("%d",&n);
if (n>10)
{
printf("You are allowed to buy maximum of 10 products"); return 0;
}
printf("Enter the price per product:\n");
//Storing the input in a 2D string first
char **str=malloc((n)*sizeof(char *));
for(int i=0;i<n;i++)
{
str[i]=malloc(NN);
}
scanf("\n");
for(int i=0;i<n;i++)
{
fgets(str[i],NN,stdin);
}
int **arr=(int **)calloc(n,sizeof(int *));
for (int i=0;i<n;i++)
arr[i]=(int *)calloc(3,sizeof(int));
//Conversion of 2D string to 2D integer array
int max;
for(int i=0;i<n;i++)
{
int num, j = 0, len;
max=j;
while ( sscanf( str[i], "%d%n", &num, &len) == 1 )
{
arr[i][j]=num;
str[i] += len;
j++;
if(j>max) max=j; //find the column size of 2D array
}
}
//Calculation of minimum possible cost
int *min,amount=0;
min=(int *)calloc(n,sizeof(min));
printf("The minimum cost of each product is as follows:\n");
for (int i=0;i<n;i++)
{
min[i]=arr[i][0];
for(int j=1;j<max;j++)
{
if (arr[i][j]<min[i])
{
min[i]=arr[i][j];
}
}
printf("%d\n",min[i]);
amount=amount+min[i];
}
printf("Total amount you need to pay Rs.%d",amount);
free(min);
for(int i=0;i<n;i++)
{
free(str[i]);
free(arr[i]);
}
free(str);
free(arr);
return 0;
}
This code works fine if the input is provided as shown above (I read each row separately and terminate the row when \n is encountered).
But how to handle the cost inputs if they are provided as follows:
Input 4
Enter the number of products:
3
Enter the price per product
100
250
500
300
450
350
Again, the column size can vary between 1 to 3 and the user does not specify the column size.
I need help regarding how to stop the array input as and when the user stops. He/She may enter 3 or 6 or 9 prices for 3 products(n=3).

fgets()size can be the same#define NN 31 ... str[i]=malloc(NN); ... fgets(str[i],NN,stdin);also no need for all that casting like(char *)cast.str[i]here ` str[i] += len;` the free cannot work