The output is 5 because the array stops incrementing index when it reaches your element 0, as john.c explained with different words.
Here is the working version of your program, "array[index]" is the value of the elements, and "index" can be used for the loop:
Code:
#include <stdio.h>
unsigned int array[]={21,22,23,12,1,0,6,7};
int main()
{
// Write C code here
unsigned int max=0;
unsigned int index=0;
while(index != 8)
{
if(array[index] > max)
{
max = array[index];
}
index++;
}
printf("max = %d\n number of elements = %d",max,index);
return 0;
}
However, I'm sure you realize the issue with counting out the elements, so we could also make a version of your program that counts the number of integer elements so that it could be compared to the array even if you change the number of elements:
Code:
#include <stdio.h>
unsigned int array[]={21,22,23,12,1,0,6,7};
int main()
{
// Write C code here
unsigned int max=0;
unsigned int index=0;
unsigned int size = sizeof(array) / 4;
while(index != size)
{
if(array[index] > max)
{
max = array[index];
}
index++;
}
printf("max = %d\n number of elements = %d",max,index);
return 0;
}
What I did was pass the array to the sizeof() function, which counts the number of bytes in the array. Since integers are 4 bytes each, we divide the number by 4 to get the number of elements.
You should also understand that null terminators are not necessary or used commonly for arrays of integers. Null terminators are just used to mark the end of a string, because otherwise your compiler will have no way of knowing when the loop ends otherwise. You don't actually need to add it yourself unless you are using a loop to make an array, if you have an array of chars, then the null terminator will get added automatically:
Code:
your_name[] = "Clearner123";
When the string is declared like that, your compiler will add the null terminator.
Also, having "while(array[index] != '\0')" is redundant, because while loops run until the condition is true or
false anyways:
Code:
while(array[index])
{
...
}
That while loop will run as long as "array[index]" does not equal zero...in programming terminology, it will
run while the condition is true. To run the loop as long as the condition is equal to zero (false), then just
add the exclamation point:
Code:
while(!array[index])
{
...
}