Thanks.
I tried implementing the same fix for my other function and got a negative result. Can anyone help explain why I'm getting the wrong value for the number of elements in the array? And also what I should work on to fix it?
Code:
void sumIntegers ()
{
int arr[100];
int i;
int num = 0;
int sum = 0;
FILE *myFile;
myFile = fopen("assignment3.txt", "w");
printf("\nI want to sum up even integers <= 50.\n\n");
do
{
printf("\n\nPlease enter a positive integer:\n\n\t\t\t");
scanf("%d", &num);
fprintf(myFile, "You chose to sum the even integers from 0 to %d.\n\n", num);
if(num < 0)
{
printf("\n*** Negative numbers are invalid! ***\n\n\n");
break;
}
for (i = num - 4; i >= 0; i--)
{
arr[i] = (i + 1) * 2; // add 1 to the index, then double it, and store that # in arr
printf ("\nIn index #%d of arr, we stored the value %d.\n", i, arr[i]); //prints arr[i] with index reference
fprintf(myFile, "%d\n\n", arr[i]); //prints to txt file
}
printf("\n");
for (i = num - 4; i >= 0; i--)
{
sum += arr[i]; // add each element to "sum"
}
printf("\n\nThe total of the %d even element in arr[i] = %d.\n\n\n\n", i, sum);
fprintf(myFile, "The sum of the %d even integers is: %d", i, sum); //prints to txt file
} while(num <= 0);
fclose(myFile);
return;
}