The issue with your program is due to the condition in your if statement and the usage of uninitialized variables when that condition is not met. Let me explain:
-
Array Indexing in C:
- In C, array indexing starts from
0. So, valid indices for an array of size dim are from 0 to dim - 1.
- Your
if condition checks for h > 0 && k > 0 && h < k. This condition excludes cases where h or k is 0, which is a valid index in C.
-
Uninitialized Variable sommafin:
- If the
if condition is not satisfied (e.g., when h is 0), the variable sommafin does not get a value assigned.
- When you then attempt to
printf("la somma degli elementi tra h e k e' %d:", sommafin);, you're using an uninitialized variable, which leads to undefined behavior and can produce unexpected results.
-
Variable-Length Arrays and Declarations in Loops:
- Make sure your compiler supports C99 or later standards since you've used variable-length arrays (
int b[dim];) and declared variables inside loops (for(int i = 0; ...)).
Here's how you can fix the issues:
Revised Code:
#include <stdio.h>
int sommaInteri(int a[], int dim, int h, int k) {
int somma = 0;
// Ensure h and k are within valid bounds
if(h >= 0 && k <= dim && h < k) {
for(int i = h; i < k; i++) {
somma += a[i];
}
} else {
printf("Indices h and k are out of bounds.\n");
}
return somma;
}
int main() {
int dim;
int h, k;
int sommafin = 0; // Initialize to 0
printf("inserire la dimensione dell' array b: ");
scanf("%d", &dim);
int b[dim]; // Ensure your compiler supports variable-length arrays
printf("inserisci %d elementi dell' array b: \n", dim);
for(int i = 0; i < dim; i++) {
scanf("%d", &b[i]);
}
printf("inserisci l' indice h: ");
scanf("%d", &h);
printf("inserisci l' indice k: ");
scanf("%d", &k);
// Adjust the condition to include 0 as a valid index
if(h >= 0 && k >= 0 && h < k && k <= dim) {
sommafin = sommaInteri(b, dim, h, k);
printf("La somma degli elementi tra h e k e' %d\n", sommafin);
} else {
printf("Gli indici h e k non sono validi.\n");
}
return 0;
}
Explanation of Changes:
Note on Variable Declarations:
- If you're using an older C compiler (pre-C99), you might need to move variable declarations to the top of the function or the beginning of the
main block since older standards don't allow declarations mixed with code.
Example Run:
inserire la dimensione dell' array b: 5
inserisci 5 elementi dell' array b:
1 2 3 4 5
inserisci l' indice h: 0
inserisci l' indice k: 3
La somma degli elementi tra h e k e' 6
Summary:
- Ensure your indices
h and k are within the valid range for your array.
- Initialize variables that may not get a value assigned due to conditional logic.
- Perform proper bounds checking both in your
main function and in any functions manipulating arrays.