factorial program in C

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • bonnieemmonsb
    New Member
    • Nov 2008
    • 1

    factorial program in C

    I code in RPG but recently took a software testing test with that included the following code:

    n! = n*((n-1)!)
    int f=1;
    if (n<0){
    fprintf(stderr, 'factorial; Negative argument.'n';
    }else if ((n==0) ||(n==1)){
    f=1;
    }else {
    f=n*factorial(-n);
    }
    return(f)
    }

    what does the statement: {else if ((n==0)||(n--1)){ mean? The question is what inputs represent test cases that would give decision coverage with the minumum number of test cases? The answer is -1, 1, 5. I understand the -1 and the 5 but not the positive 1. I thought the answer would be -1, 0, 5. I code in RPG not in C so I attributed my incorrect answer to my lack of knowledge of C. Any help would be much appreciated.
  • oler1s
    Recognized Expert Contributor
    • Aug 2007
    • 671

    #2
    > what does the statement: {else if ((n==0)||(n--1)){ mean?
    Else if (n is 0) or (n is 1):

    The answer is -1, 1, 5. I understand the -1 and the 5 but not the positive 1. I thought the answer would be -1, 0, 5. I code in RPG not in C so I attributed my incorrect answer to my lack of knowledge of C.
    I doubt your answer was wrong because of not knowing C. Actually, between their answer and your answer, I would favor yours. They have 1 and 0 as a base case for factorial, but it is possible to implement factorial with only 0 as a base case. For that reason, 0 should be tested, and 1 can be omitted.

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      It means that both 0! and 1! are 1.

      Without this test, the recursion would be ininfite.

      Comment

      • svlsr2000
        Recognized Expert New Member
        • Feb 2007
        • 181

        #4
        by the way you should be having f=n*factorial(n-1); instead of f=n*factorial(-n);

        Comment

        • Ganon11
          Recognized Expert Specialist
          • Oct 2006
          • 3651

          #5
          Unless he forgot to type in an extra - making it f=n*factorial(--n);

          Comment

          Working...