You're online now.

Hurray! you are online now.

Write a C program generate and prints the Fibonacci series up to a user-defined limit

The program generates and priints the Fibonacci series up to a user-defined limit.

#include<stdio.h>
    int main()}
    	int n;
    	printf("Enter the number : ");
    	scanf("%d", &n);
    	int a = 0, b = 1;
    	printf("%d %d", a, b);
    	for(int i = 3; i <= n; i++){
    		int c = a + b;
    		printf("%d", c);
    		a = b;
    		b = c;
    	}
    	return 0;
    }
#include<stdio.h>

Includes the standard library for using the input/output inbuild operation

int main(){

Enter point of the program, which called in c program main() function.

int n;

‘n’ is declaring a variable ‘n’ of type integer. This variable will be used to store the user-defined limit up to which the Fibonacci series will be generated and printed.

printf("Enter the number : ");

Prompt to the user enter the number using the printf() function.

scanf("%d", &n);

Reads input from the user using the scanf() function.

int a = 0, b = 1;

Set a  = 0, b = 1, we know above the fibonacci series where first two number is start 0 and 1 first two number of the fibonacci series.

printf("%d %d ", a,b);

‘printf("%d %d", a, b);’ is printing the first two numbers of the Fibonacci series, which are stored in variables ‘a’ and ‘b’.The ‘%d’ format specifier is used to print integer values.

for(int i = 3; i <=n; i++){
    	int c = a + b;
    	printf("%d", c);
    	a = b;
    	b = c;
    }

The ‘for’ loop is iterating from 3 to ‘n’, where ‘n’ is the user-defined limit up to which the Fibonaccci series will be generated and printed. Inside the loop, the variable ‘c’ is declared and assigned the sum of the previous two number in the Fiboanacci series, which are stored in varialbes ‘a’ and ‘b’. Then, the value of ‘c’ is printed using the ‘printf()’ function. Finally, the values of ‘a’ and ‘b’ are swapped, where the value of ‘b’ is assigned to ‘a’ and the value of ‘c’ is assigned to ‘b'. This is done so that the last number of the series becomes the second-to-last number in the next iteration of the loop.

return 0;
    }

Return 0, which means that program is successfully executed.

Algorithm

1. Start
2. Declared n as integer
3. Reads the number from user
4. Set a = 0, b = 1
5. Display a and b
6. for from 3 to n
    1. Set c = a + b
    2. Display c
    3. Set a = b
    4. Set b = c
7. Exit

Pseudocode

1. INCLUDE stdio.h
2. FUNCTION main()
    1. DECLARED n AS INTEGER
    2. PRINT "Enter the number"
    3. READ n FROM USER
    4. SET a = 0, b = 1
    5. PRINT a and b
    6. FOR 3 to n
        1. SET c = a + b
        2. PRINT c
        3. SET a = b
        4. SET b = c
    7. RETURN 0
🖤 0
Buy me coffee ☕

Comments

Oops!

No comments here...