Homework 1

From CS113

Contents

Factorial

The factorial of a positive number N is defined as the product 1*2*3*...*N.


For example, factorial of 5 is 1*2*3*4*5 = 120, and factorial of 10 is 1*2*3*4*5*6*7*8*9*10 = 3628800


Q1: Write a program to compute the factorial of a number using for-loops.

Example output

[netid@submit cs113]$ ./fact 5
120
[netid@submit cs113]$ ./fact 10
3628800
  • You will accept a number N as a command line argument
  • Your program will print the factorial of N as output
  • You do NOT need to handle bad input (i.e. negative numbers, non-integer arguments etc.)

Q2: Now write the same program without using loops (hint: use recursion)

[netid@submit cs113]$ ./fact2 5
120
[netid@submit cs113]$ ./fact2 10
3628800

Fibonacci

The fibonacci sequence is a sequence that beings with 1, 1, and continues such that each number is the sum of the previous two numbers. The sequence goes as follows: 1, 1, 2, 3, 5, 8, 13, 21, ...


Q3: Write a program to compute the N-th fibonacci number.

Example output

[netid@submit cs113]$ ./fib 1
1
[netid@submit cs113]$ ./fib 2
1
[netid@submit cs113]$ ./fib 5
5
[netid@submit cs113]$ ./fib 8
21
  • You will accept a number N as a command line argument
  • Your program will print the N-th Fibonacci number as output
  • You do NOT need to handle bad input (i.e. negative numbers, non-integer arguments etc.)

Q4: Now write the same program without using loops (hint: use recursion)


[netid@submit cs113]$ ./fib2 1
1
[netid@submit cs113]$ ./fib2 2
1
[netid@submit cs113]$ ./fib2 5
5
[netid@submit cs113]$ ./fib2 8
21

Submission Instructions

Homeworks will be individual work, however, you may consult with your peers.

Create your workspace as shown on the Get Started page.

Save your homework submission under the names fact.c, fact2.c, fib.c, fib2.c under your cs113 directory.

Hints

  1. See how to Write Your First C Program for hints on how to read command line arguments, convert them into integers, and print to the screen.
  2. Use the atoi function to convert a string argument to an integer.
  3. Use the printf function to print to the screen
  4. If you run into an infinite loop, use <ctrl>-C to stop the program.
    • If that doesn't work, log into the machine from another SSH window and run killall fact (replace fact with the name of your program)
    • If even that doesn't work, email saikat@cs.cornell.edu
Personal tools
Navigation