These declarations
int no, i,j, product = 1;
int* ar1 = (int*)malloc(sizeof(int) * no);
int* ar2 = (int*)malloc(sizeof(int) * no);
invoke undefined behavior because the variable no is not initialized and has indeterminate value.
At first you should ask the user how many elements in the array he wants and only after that to allocate dynamically arrays or use variable length arrays.
These loops
for(i=0; i<no; i++){
for(j=0; j<no; j++){
while(j!=i){
product=ar1[i]*product;
}
}
ar2[i]=product;
}
are also invalid. For example the inner while loop can be infinite. And the variable product
should be initialized in each iteration of the outer loop.
In this loop
for(i=0; i<no; i++){
printf("The output array is: \n");
printf("%d", ar1[i]);
}
this call pf printf
printf("The output array is: \n");
should be outside the loop and in this call of printf
printf("%d", ar1[i]);
you have to use ar2
instead of ar1
.
Also declare variable where they are used. Otherwise it is difficult to understand their meanings when you do not see at once where they are used.
Here is a demonstrative program.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
printf( "Enter the number of elements in array: " );
size_t n = 0;
scanf( "%zu", &n );
int *a1 = malloc( n * sizeof( int ) );
long long int *a2 = malloc( n * sizeof( long long int ) );
printf( "Enter the elements: " );
for ( size_t i = 0; i < n; i++ )
{
scanf( "%d", &a1[i] );
}
for ( size_t i = 0; i < n; i++ )
{
a2[i] = 1;
for ( size_t j = 0; j < n; j++ )
{
if ( i != j ) a2[i] *= a1[j];
}
}
printf( "The output array is: " );
for ( size_t i = 0; i < n; i++ )
{
printf( "%lld ", a2[i] );
}
putchar( '\n' );
free( a1 );
free( a2 );
return 0;
}
The program output might look like
Enter the number of elements in array: 10
Enter the elements: 1 2 3 4 5 6 7 8 9 10
The output array is: 3628800 1814400 1209600 907200 725760 604800 518400 453600 403200 362880
Pay attention to that as a product of elements of an array can be very big then it is better to allocate the second array as having the element type long long int
to avoid an overflow.