FACTORIAL AND FIBONACCI PROGRAM IN C
C Program to Find First N Fibonacci Numbers
/*
* C program to generate and print first N FIBONACCI numbers
* in the series.
*/
#include <stdio.h>
void main()
{
int fib1 = 0, fib2 = 1, fib3, num, count = 0;
printf("Enter the value of num \n");
scanf("%d", &num);
printf("First %d FIBONACCI numbers are ...\n", num);
printf("%d\n", fib1);
printf("%d\n", fib2);
count = 2; /* fib1 and fib2 are already used */
while (count < num)
{
fib3 = fib1 + fib2;
count++;
printf("%d\n", fib3);
fib1 = fib2;
fib2 = fib3;
}
}
$ cc pgm10.c
$ a.out
Enter the value of num
15
First 15 FIBONACCI numbers are ...
0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
C Program to Compute First N Fibonacci Numbers using Command Line Arguments
/*
* C Program to Compute First N Fibonacci Numbers using Command Line Arguments
*/
#include <stdio.h>
/* Global Variable Declaration */
int first = 0;
int second = 1;
int third;
/* Function Prototype */
void rec_fibonacci(int);
void main(int argc, char *argv[])/* Command line Arguments*/
{
int number = atoi(argv[1]);
printf("%d\t%d", first, second); /* To print first and second number of fibonacci series */
rec_fibonacci(number);
printf("\n");
}
/* Code to print fibonacci series using recursive function */
void rec_fibonacci(int num)
{
if (num == 2) /* To exit the function as the first two numbers are already printed */
{
return;
}
third = first + second;
printf("\t%d", third);
first = second;
second = third;
num--;
rec_fibonacci(num);
}
$ cc arg6.c
$ a.out 10
0 1 1 2 3 5 8 13 21 34
Factorial Program in C
/*
* C program to find the factorial of a given number using for loop.
*/
#include <stdio.h>
void main()
{
// fact to store factorial of number N
int fact = 1, n;
// Take input
printf("Enter the number: \n");
scanf("%d", &n);
// Check validity of N
if (n <= 0)
fact = 1;
// Loop N times and multiply all positive numbers
else
{
for (int i = 1; i <= n; i++)
{
fact = fact * i;
}
}
// Print the fact.
printf("Factorial of %d = %5d\n", n, fact);
}
Runtime Test Cases
Here is the runtime output of a C program to find the factorial of a number when the number entered by the user is “6”.
Enter the number: 6
Factorial of 6 = 720
C Program to Find the Factorial of a Number using Recursion
/*
* C Program to find factorial of a given number using recursion
*/
#include <stdio.h>
int factorial(int);
int main()
{
int num;
int result;
printf("Enter a number to find it's Factorial: ");
scanf("%d", &num);
if (num < 0)
{
printf("Factorial of negative number not possible\n");
}
else
{
result = factorial(num);
printf("The Factorial of %d is %d.\n", num, result);
}
return 0;
}
int factorial(int num)
{
if (num == 0 || num == 1)
{
return 1;
}
else
{
return(num * factorial(num - 1));
}
}
Runtime Test Cases
$ cc pgm5.c
$ a.out
Enter a number to find it's Factorial: 6
The Factorial of 6 is 720.