0

I want to create an array which displays the element that many times as the entered frequency. I wrote the following code

printf("Enter the number of 5 kg cartons: ");
scanf("%d",&c5);
printf("Enter the number of 10 kg cartons: ");
scanf("%d",&c10);

int x=c5+c10;
int cartons[x],i,j;

for(i=0;i<c5;i++){
        cartons[i]= 5;
for(j=i;j<c10;j++){
        cartons[j]= 10;
}
}

I want the Out put to be the following if I give c5 and c10 the value 2: 5 5 10 10

  • Because you are declaring `int i` within the first `for` loop, it will not necessarily exist after the loop. You don't generate output anywhere, so don't expect to see anything. – Cheatah Nov 12 '22 at 17:11
  • @Cheatah I did as you suggested but I can't still reach the answer. I guess there is a problem in the for loop condition but I can't point it out. if you can point it out it will be a great help as this is for my project. – Ayushi kumar Nov 12 '22 at 17:26

1 Answers1

0

Try to use below for loop:

'i' variable used as counter in for loop can be initialised inside as we will use it only in this for loop

for(int i = 0; i < x; i++)
{
    cartons[i] = i < c5 ? 5 : 10;
}

instead of nesting for loops. Below whole example:

printf("Enter the number of 5 kg cartons: ");
scanf("%d",&c5);
printf("Enter the number of 10 kg cartons: ");
scanf("%d",&c10);

int x=c5+c10;
int cartons[x];

for(int i = 0; i < x; i++)
{
    cartons[i] = i < c5 ? 5 : 10;
}
eRtuSa
  • 46
  • 5