Reputation: 389
I am working on a project where I must creat a matrice and initialize it.
So this is what I have done to init
the matrice :
int levenshtein(char *string1, char *string2)
{
int32_t firstWord = strlen(string1);
int32_t secondWord = strlen(string2);
int32_t matrice[MAXWORD][MAXWORD]; //MAXWORD = 155
int32_t i = 0;
int32_t j = 0;
while (i++ < MAXWORD)
{
matrice[i][0] = i;
matrice[0][i] = i;
}
}
So when I print the matrice I should get in matrice[0][0] = 0
, matrice[1][0] = 1
etc
But when I print the matrice everything will be good exepte that matrice[1][0]
it is equal to MAXWORD
.
But if increment like this it while work perfectly
while (i < MAXWORD)
{
matrice[i][0] = i;
matrice[0][i] = i;
i++
}
Why the while (i++ < MAXWORD)
will change the result of matrice[1][0]
(and only matrice[1][0]
) after exiting the while
?
Upvotes: 2
Views: 65
Reputation: 781593
WHen you do the increment in the while()
statement, you're adding 1
to i
before you enter the body of the loop. So on the first iteration, the value of i
will be 1
, not 0
. That's why you never initializematrice[0][0]
.
Moving the increment to the end of the loop means you enter it with the current value. So the first time through the loop i
will be 0
, not 1
.
A better way to loop through a range of values is with for
, not while
:
for (i = 0; i < MAXWORD; i++) {
matrice[i][0] = i;
matrice[0][i] = i;
}
Upvotes: 1
Reputation: 76
It is because of the postincrement operator, first reads the value of your variable, and increments it by one after reading the value so in your code, the i variable will be < than MAXWORD when you do the comparison in the while, and will be equal to MAXWORD when enters the while body.
Hope that this will help you.
Upvotes: 0