1.Factorial of a number:
/* C program to display factorial of an integer if user enters
/* C program to display factorial of an integer if user enters
non-negative integer. */
#include <stdio.h>
main()
{
int n, count;
float factorial=1;
printf("Enter an integer: ");
scanf("%d",&n);
if ( n< 0)
printf("Error!!! Factorial of negative number doesn't exist.");
else
{
for(count=1;count<=n;count++) /* for loop terminates if count>n */
{
factorial*=count; /* factorial=factorial*count */
}
printf("Factorial = %f",factorial);
}
}
Output 1
Enter an integer: -5 Error!!! Factorial of negative number doesn't exist.
Output 2
Enter an integer: 10 Factorial = 3628800
2.Fibonacci series
/* Displaying Fibonacci sequence up to nth term where n is entered by user. */#include <stdio.h> int main() { int count, n, t1=0, t2=1, display=0; printf("Enter number of terms: "); scanf("%d",&n); printf("Fibonacci Series: %d+%d+", t1, t2); /* Displaying first two terms */ count=2; /* count=2 because first two terms are already displayed. */while (count<n) { display=t1+t2; t1=t2; t2=display; ++count; printf("%d+",display); } return 0; }
Output
Enter number of terms: 10 Fibonacci Series: 0+1+1+2+3+5+8+13+21+34+
No comments:
Post a Comment