Reputation: 33
I have this code:
void main()
{
int x;
scanf("%d", &x);
int array[x];
int i;
for(i=0; i<x; i++)
{
scanf("%d", &array[i]);
}
int j;
for(i=0; i<x-1; i++)
{
if(array[i]>=array[i+1])
j=array[i];
else j=array[i+1];
}
printf("%d", &j);
}
And I want to print the biggest number in the array. But it always returns a giant random number and I'm struggling to find my mistake here. Any help would be appreciated. Thanks in advance.
Upvotes: 0
Views: 139
Reputation: 67476
int max(int *a, size_t size)
{
int max = INT_MIN;
size_t i = 0;
while(i < size)
{
if(a[i] > max) max = a[i] ;
i++;
}
return max;
}
Upvotes: 0
Reputation: 31
Do something like this
void main()
{
int x;
scanf("%d", &x);
int array[x];
int i;
for(i=0; i<x; i++)
{
scanf("%d", &array[i]);
}
int j = a[0];
for(i=1; i<x; i++)
{
if(array[i] > j)
j=array[i];
}
printf("%d", j);
}
You are comparing two consecutive elements of array
array[i] >= array[i+1]
which is not the correct logic. You should compare each element of array with biggest number found yet (as storing in j)
array[i] > j
Also you cannot pass address of variable to printf() function. It should be like this
printf("%d", j);
Upvotes: 0
Reputation: 310930
Change this code snippet
int j;
for(i=0; i<x-1; i++)
{
if(array[i]>=array[i+1])
j=array[i];
else j=array[i+1];
}
printf("%d", &j);
^^^
the following way
int j = array[0];
for ( i = 1; i < x; i++ )
{
if ( j < array[i] ) j = array[i];
}
printf( "%d", j );
^^^
The original code snippet does not search the greatest element (consider fpr example an array containing the following elements { 5, 4, 3, 2, 1 }
) and the second argument of the call of printf is specified incorrectly.
Take into account that the name x
is not suitable for the number of elements in an array. It is much better to use for example the name n
.
Also according to the C Standard the function main
without parameters shall be declared like
int main( void )
Upvotes: 1
Reputation: 12972
You have probably messed up scanf
and printf
. scanf
requires a pointer e.g
scanf("%d", &j);
(in order to change the value of the variable) but in printf you shouldn't pass a pointer so printf("%d", &j);
should be printf("%d", j);
(since printf
only prints the value of the variable and doesn't change it)
Upvotes: 2