/*Given an array arr[] of n integers, construct a Product Array prod[] (of same size) such that prod[i] is equal to the product of all the elements of arr[] except arr[i].

My code is printing garbage value.Pls someone suggest me what is wrong and how can I correct it..Thank you */

include<stdio.h>
main()
{
int i,j,a;
 int sum=1;
int vari=1;
 int array[5]={1,2,3,4,5};

int temp[4];
while(a<=4)
{
printf("sum");
for(i=0;i<=4;i++)
{
    if(i==a)
    i++;
    else 
    sum=sum*array[i];

}
temp[j]=sum;
j++;
a++;
sum=vari;
}

for(j=0;j<=4;j++)
printf("%d\n",temp[j]);

}

line 9: what's the value of variable a???

line 20: what's the value of variable j??

Answer: both i and j are uninitialized variables, so their value can be any random number.

You've started coding, before you finished thinking about how it should be done.

The array name should be arr[], not array[], correct?

Think of the logic:

make an array prod[] equal in size to arr[]. Do you know how to use malloc()?

Then

for(each value in arr[] except the current value you are on as you traverse through the array of arr[])

multiply all the other values in arr[]
and put that value into prod[i]

end of for loop

Is that what you need to do?

thank you @Ancient Dragon..did a silly mistake..will take care of it now..
thank you Adak used malloc for dynamic allocation in my code.

void main()

{


int i,j,swap=1;
int arre[5],prod[5];
clrscr();
printf("nter values in the array ");
for(i=0;i<5;i++)
    scanf("%d",&arre[i]);

for(j=0;j<5;j++)
{
    for(i=0;i<5;i++)
    {
        if(i==j)
            continue;
        else
            swap=swap*arre[i];
    }
    prod[j]=swap;
    swap=1;
}

printf("The output is ");
for(j=0;j<5;j++)
    printf("%d",prod[j]);

    getch();


}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.