Reputation: 1343
I have just started learning C today, not very used to the syntax since previously I had only been using Python. I have this assignment.
Write a function that returns the sum of first n numbers in num_array of size 10. If n is an invalid number (i.e. not within 0 to 10 inclusive), return the value -1 instead to indicate an error.
Here's my attempt, which is not working for some reason. I don't have a proper IDE to check my code as I do not know any free newbie friendly IDEs for beginners. Can anyone tell me what went wrong here?
int num_array[10] = {3, 4, 6, 1, 0, 9, 8, 6, 2, 5};
int nth_sum_of_num_array(int n) {
if !(0 <= n <= 10) {
return -1;
}
else {
int result = 0;
for (int i = 0; i < n; i++) {
result += num_array[i];
}
return result;
}
}
I would also appreciate suggestions on a free and newbie friendly C IDE with compilers.
Upvotes: 0
Views: 134
Reputation: 26647
You just need to change the condition:
#include <stdio.h>
int num_array[10] = {3, 4, 6, 1, 0, 9, 8, 6, 2, 5};
int nth_sum_of_num_array(int n) {
if (n > 9|| n < 0) {
return -1;
} else {
int result = 0;
for (int i = 0; i < n; i++) {
result += num_array[i];
}
return result;
}
}
int main(void) {
printf("The result is %d", nth_sum_of_num_array(6));
}
BTW, for a good C IDE, try clion.
Upvotes: 2
Reputation: 43098
This may work in python:
if !(0<=n<=10)
But not in C. This is how you do it in C:
if (n <= 0 || n >= 10) {
Each condition has to be separated by a logical operator.
Upvotes: 2