Question

1 Attachment
EE140 Intro to Programming Concepts for Engineers Lab 7 Please turn in the assignment electronically, as usual. Please turn in a tar archive of a directory called assignment_7; turn in code and executables for the remaining problems named question1.txt, question2.c, question2.out, etc. Make a compressed tarball of the directory, call it LastnameFirstname_lab7_XXXX.tar.gz and copy it to my dropbox. Questions 1 and 4 require only a .txt file (written paragraph answer); Questions 2 and 3 require running code (.c and .out files) 1. EXAMPLE: 2 For a positive integer number n, its factorial (n!) is given by: n! = 1 (for n=1) n! = n (n-1)! (for n>1) Write a program to calculate n! using a recursive function. int factorial (int n); // function prototype of factorial() If n is 1, factorial (1) returns 1 If n > 1, factorial (n) returns n * factorial (n-1) Continue recursion until n is 1 #include<stdio.h> //a recursive factorial function int factorial( int n ) { if (n <= 1) return 1; else return( n * factorial( n -1)); } int main( void) { int n, result ; printf("Enter Value for n: "); scanf("%d", &n); //enter value n result = factorial (n); //call factorial() to compute n! printf("%d !=%d\n", n, result); return 0; } EXAMPLE: 3 #include<stdio.h> // a non-recursive (iterative) factorial function int factorial(int n ) { int i, prod = 1; for (i=1; i<=n; i++) prod = prod * i; return prod; } int main( void) { int n; printf("Enter Value for n: "); scanf("%d", &n); //enter value n printf("%d !=%d\n", n, factorial(n)); return 0; } Review Example 2 and Example 3 and compare the recursive function implementation with the non-recursive function implementation. For this question, just write a short paragraph explaining how the two implementations are different. (saying “ one’s recursive and the other isn’t ” doesn’t get you any points) 2. Write a recursive function to determine and return the sum of the first n positive integers. Read the value of n from the keyboard. (For example, for n=100 the sum is 5050) 3. The greatest common divisor of integers x and y is the largest integer that evenly divides both x and y. Write a recursive function gcd() that returns the greatest common divisor of x and y. The gcd of x and y is defined recursively as follows: if y is equal to 0, then gcd (x, y) is x; otherwise gcd (x, y) is gcd (y, x%y) where % is the remainder operator. (question 4 is on the next page) End of preview

1 Attachment zip  