function

This is a discussion on function within the C Programming forums, part of the General Programming Boards category; Hi, There is this exercise which I have to make an own function in it. It goes like this: sum(n) ...

  1. #1
    Registered User
    Join Date
    Nov 2007
    Posts
    25

    Unhappy function

    Hi,
    There is this exercise which I have to make an own function in it.
    It goes like this:
    sum(n) = 1+2+3+...+n
    Here is the code I wrote. I get a syntax error in line 14. also an error in line 13 which says that variabel "dsum" is unused!!
    Where in program should I make changes? Appreciate it a alot if someone can give me a clue!

    Code:
    #include<stdio.h>
    #include<stdlib.h>
    #include<stdbool.h>
    int sum(int i);
    int main()
    {
      printf("%d\n",sum(5));
      return 0;
    }
    int sum(int i)
    {
      int r = 1;
      int dsum = 0;
      for(r<=i){
        dsum += r;
        r++;
      }
      return sum;
    }

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    The syntax for your "for" loop is incorrect. The correct syntax is
    Code:
    for(initialization ; exit-condition ; update)
    You can omit any of the three components, but you DO need the semicolons - and an empty exit-condition means "always true".

    Once the compiler got confused by the lacking semi-colons, it may not realize what the rest of that loop does, and "undefined behaviour" applies.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Registered User
    Join Date
    Nov 2007
    Posts
    25
    Quote Originally Posted by matsp View Post
    The syntax for your "for" loop is incorrect. The correct syntax is
    Code:
    for(initialization ; exit-condition ; update)
    You can omit any of the three components, but you DO need the semicolons - and an empty exit-condition means "always true".

    Once the compiler got confused by the lacking semi-colons, it may not realize what the rest of that loop does, and "undefined behaviour" applies.

    --
    Mats

    Thanks alot for d answer =)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Compiling sample DarkGDK Program
    By Phyxashun in forum Game Programming
    Replies: 6
    Last Post: 01-27-2009, 02:07 AM
  2. Seg Fault in Compare Function
    By tytelizgal in forum C Programming
    Replies: 1
    Last Post: 10-25-2008, 03:06 PM
  3. Another syntax error
    By caldeira in forum C Programming
    Replies: 31
    Last Post: 09-05-2008, 01:01 AM
  4. Replies: 28
    Last Post: 07-16-2006, 11:35 PM
  5. const at the end of a sub routine?
    By Kleid-0 in forum C++ Programming
    Replies: 14
    Last Post: 10-23-2005, 06:44 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21