Menu

PROBLEM TO DECLARE A FUNCTION

2010-01-23
2012-09-26
  • anik naruto

    anik naruto - 2010-01-23

    what is the problem of following code ?

    include<stdio.h>

    include<stdlib.h>

    fac();
    main()
    {long int a,d,e;
    scanf("%ld",&a);
    scanf("%ld",&d);
    e=fac(a)/(fac(b)*fac(a-b));
    printf("%ld",e);
    system("pause");

    }
    fac(int p)
    {long int p,b,c;
    for(c=1;c<=p;c++){b=b*c;
    }
    return b;

    }

     
  • anonymous nobody

    Lots of things.
    1. Each function must have a return type.
    2. Prototypes must list arguments.
    3. long int is not a type. long and int are, but not long int.
    4. Here is your fixed code:

    #include <cstdio>
    #include <cstdlib>
    int fac(int p);
    int main() {
        int a, b, c;
        scanf("%d", &a);
        scanf("%d", &b);
        c = fac(a)/fac(b)*fac(a-b);
        printf("%d", c);
        system("pause");
        return 0;
    }
    int fac(int p) {
        int a, b;
        for(a = 1; a <= p; ++a) {
            b *= a;
        }
        return b;
    }
    
     
  • cpns

    cpns - 2010-01-28

    drmoo
    2010-01-28 03:52:17 GMT
    1. Each function must have a return type.

    In C89 the original code is valid in this respect (but probably produces a
    warning).

    drmoo
    2010-01-28 03:52:17 GMT
    2. Prototypes must list arguments.

    Again in C89 the original code is valid, and empty argument list means
    "undefined number of arguments". This is not true however of C++ or I believe
    C99.

    drmoo
    2010-01-28 03:52:17 GMT
    3. long int is not a type. long and int are, but not long int.

    Not true in either C or C++, long _is a synonym for _long int.

    drmoo
    2010-01-28 03:52:17 GMT
    4. Here is your fixed code:

    You should be cautious of perhaps having just done someone's homework
    assignment for them! In this case a better response would be to have asked the
    OP to elaborate by telling us why he thinks it is incorrect, and what compiler
    messages he gets or what results he gets when it runs.

    The real problems are the ones you did not mention (but some of which you
    fixed any way):

    1) The variable b is referenced in main() but not defined, while d remains
    unused.
    2) fac() bith takes a parameter p and defines a local variable p
    3) In fac() b is not initialised, so the results will be undefined.

    All of the above issues would have been reported by the compiler (I used
    VC++2008), so use of a compiler would have given the OP his answer (which is
    why this looks like homework, along with the laziness of the question).

     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.