Program to generate Fibonacci series
#include#include #include void main() { clrscr(); //Declare an initialize the variables int firstNum = 0, secondNum = 1, fibNum, temp; //Accept a number from the user printf("\nEnter the number: "); scanf("%d", &fibNum); /*Exit if value is less than 2*/ if(fibNum <=1) { printf("\nPlease enter a number greater than 1."); getch(); exit(0); } //Display first two number of the series printf("\nFibonacci series:\n"); printf("%d %d ", firstNum, secondNum); for(int i = 1; i<=fibNum-2; i++) { temp = firstNum + secondNum; printf("%d ",temp); firstNum = secondNum; secondNum = temp; } getch(); }
Output:
Enter the number: 20 Fibonacci series: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
great idea!!!!
/* 03_generate_for_if.c
2 *
3 * the Fibonacci Sequence are the numbers
4 * in the folowing integer sequence.
5 * 0 1 1 2 3 5 8 13 21 34 55 89 144 …
6 *
7 * starting whith 0 and 1 and each subsequent number
8 * is the some of the previous two.
9 *
10 * 0 + 1 = 1 1 + 1 = 2 1 + 2 = 3 2 + 3 = 5 3 + 5 = 8 …
11 * – – – – – –
12 */
13
14 #include
15 #include
16
17
18 int main()
19 {
20 int firstNum = 0, secondNum = 1; //fibonacci sequance starts with 0, 1
21 int fibNumtoDis, fibSeq; //fibNumtoDis: the amount of digit to display, fibSeq: help us add to the n
22
23 // get a number from the user to start the sequence
24 printf(“Enter the amount of fibonacci number to display: “);
25 scanf(“%d”, &fibNumtoDis);
26
27 // exit if number is less than one
28 if(fibNumtoDis <= 1)
29 {
30 printf(“The number you entered [%d] is to samall\n\n”, fibNumtoDis);
31 printf(“Good Bye! \n”
32 exit(0);
33 }
34
35 // display the first two number of the series
36 printf(“\nFibonacci Sequence:\n”);
37 printf(“%d, %d “, firstNum, secondNum); // 0, 1,
38
39 // for() loop until the number to display is reached
40 int i;
41 for(i = 1; i <= fibNumtoDis - 2; i++) // -2 because 0, 1 will display authomaticly
42 {
43 //
44 fibSeq = firstNum + secondNum; // add the first 2 number.
45
46 printf(“, %d”, fibSeq); // display the result
47
48 firstNum = secondNum; // make the second number equal the first
49 secondNum = fibSeq; // make the second number equal to fibseq
50
51 }
52 printf(“\n”);
53 }
In the for loop why the loop runs fibnum-2 times?