First of all, value[].length]
is not permissible in C to determine the length of an array. As side note there is also an abandoned ]
after length
which would give you a syntax error, even if you would use a C++ compiler to compile this code.
If you want to get the amount of elements you need to use f.e. the sizeof
operator and divide the amount of allocated memory in bytes by the memory per element object:
sizeof(value) / sizeof(value[0])
Furthermore the algorithm of the inner for
loop
j = value[0]; j <= value[].length; j++){
makes no sense. Why would you want to compare the value at a certain array element with the length of the whole entire array instead of to iterate over the array until the matched value is found?
Think about what you are doing!
You also need another if
check to proof it you encountered the right value.
For example:
#include <stdio.h>
int main (void) {
unsigned int j;
unsigned int days = 1;
unsigned int value[] = {
31,30,29,28,27,26,
25,24,23,22,21,20,
19,18,17,16,15,14,
13,12,11,10,9,8,7,
6,5,4,3,2,1
};
unsigned int len = sizeof(value) / sizeof(value[0]);
printf("Day \t Index \t Value\n");
for (days = 1; days <= 31; days++) {
for (j = 0; j < len ; j++) {
if (value[j] == days)
printf("%u \t %u \t %u\n", days, j, days);
}
}
}
Output:
Day Index Value
1 30 1
2 29 2
3 28 3
4 27 4
5 26 5
6 25 6
7 24 7
8 23 8
9 22 9
10 21 10
11 20 11
12 19 12
13 18 13
14 17 14
15 16 15
16 15 16
17 14 17
18 13 18
19 12 19
20 11 20
21 10 21
22 9 22
23 8 23
24 7 24
25 6 25
26 5 26
27 4 27
28 3 28
29 2 29
30 1 30
31 0 31
Side Notes:
I used unsigned int
because it is unusual that you have negative days and it is better for the comparison with the return of the sizeof
operation to determine the length of the array value
.
The formatting of the output can be different on your implementation because how many spaces \t
is exactly, is implementation-specific.
Use a C compiler to compile C code and never ignore compiler warnings. Don't intermix C with C++ code.
Use int main(void)
instead of int main()
. The latter is not strict C standard-compliant.
Good and free C starting books are Modern C or The C Programming Language (2nd Edition). These and others you can find here:
The Definitive C Book Guide and List