Reputation: 3
h_array[i] is less than 19 for the first few cases. However, it still prints k as 0. Could someone help me out as to why this happens?
for (int i = 0; i < 10; i++) {
int j = h_array[i];
int k = 0;
if (h_array[i]<19) {
int k = 20 - j;
}
int l = 20;
while (l>=k) {
printf ("%d - %d\n\n\n",l,k);
l--;
}
}
Upvotes: 0
Views: 556
Reputation: 1030
Its because of the scope visibility of the variable int k
Your code has 2 int k
. An outer k
and an inner k
. When the k
inside the if statement goes out of scope, the value being printed is the value of the outer k
, which in this case is 0
.
The correct solution would be:
k = 20 - j;
Not :
int k = 20 - j;
Upvotes: 1
Reputation: 6075
The issue is you've re-declared 'k' inside the body of the if statement. The compiler will usually generate a warning about this.
In this case the 'k' variable with the scope of the condition body is modified, whilst the 'k' in the parent scope retains its original value (0).
Removing the type specifier should fix the issue.
for (int i = 0; i < 10; i++) {
int j = h_array[i];
int k = 0;
if (h_array[i]<19) {
k = 20 - j;
}
int l = 20;
while (l>=k) {
printf ("%d - %d\n\n\n",l,k);
l--;
}
}
Upvotes: 3