0

I'm writing a program that adds the numbers from 1-5 and prints out the sum. It was working a week ago but today I got unused variable error and don't know where i'm wrong.

int main(int argc, const char * argv[]) {
    int sum = 0;
    int num;
    for(int num=1; num<=5; num++){
        sum = sum + num;
    }
    printf(" The sum of numbers 1 to 5 are %d",sum);

    return 0;
}
Andrew Li
  • 55,805
  • 14
  • 125
  • 143
J.Doe
  • 29
  • 4

1 Answers1

1

You first declare a num variable of type int, and then redeclare it in the for loop.

So you should either remove the int in the for loop (C89):

int main(int argc, const char * argv[]) {
    int sum = 0;
    int num;
    for(num=1; num<=5; num++){
        sum = sum + num;
    }
    printf(" The sum of numbers 1 to 5 are %d",sum);

    return 0;
}

Or remove the num variable first declaration (C99):

int main(int argc, const char * argv[]) {
    int sum = 0;
    for(int num=1; num<=5; num++){
        sum = sum + num;
    }
    printf(" The sum of numbers 1 to 5 are %d",sum);

    return 0;
}

You compiler may also say "Unused variable" because you do not use the main function parameters (argc and argv). You can fix this by using main(void):

int main(void) {
    /* ... */
paly2
  • 11
  • 2