Question

I am following an example from CUNY and I have never done anything with C before so I probably don't know what I am doing.

Consider the program below.

  1. Do I need a shebang line for C code written in emacs?
  2. When I go to compile using the line gcc -g -o forwardadding forwardadding.c I am hit with the message:

    forwardadding.c:9:17: error: expected expression before ‘<’ token
    
  3. Once I get the code compiles, I can use gdb to debug and run the code corrrect?

The code:

#include <stdio.h>
#include <math.h>

main()
{
    float sum, term;
    int i;
    sum = 0.0;
    for( i = 1; < 10000000; i++)
    {
        term = (float) i;
        term = term * term;
        term = 1 / term;
        sum += term;
    }
    printf("The sum is %.12f\n", sum);
}
Was it helpful?

Solution 2

You need to put a variable in the for loop for a complete expression (which is probably line 9...)

for( i = 1; < 10000000; i++)

change to this

for( i = 1; i < 10000000; i++)

OTHER TIPS

  1. No shebang is needed. You could add an Emacs mode line comment.

  2. The for loop should be:

    for (i = 1; i < 10000000; i++)
    

    Your code is missing the second i.

  3. Yes, you can use GDB once you've got the code compiling.

You'd get a better answer to the mathematics if you counted down from 10,000,000 than by counting up to 10,000,000. After about i = 10000, the extra values add nothing to the result.

Please get into the habit of writing C99 code. That means you should write:

int main(void)

with the return type of int being required and the void being recommended.

You are missing an an i. Just correct that as Jonathan Leffler has suggested and save your file. Open your terminal and just use this to compile your code gcc your_file_name.c and your code compiles next to run the code that just compiled type ./a.out and your program runs and shows you the output.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top