MeetCode
Nth Fibonacci (iterative)
C
C++
Computer Mathematics
CSS
DSA
HTML
Java
JavaScript
NodeJS
PHP
Programming Interview
Python
ReactJS
SQL
Run
Submit
Dark
Problem Statement
Solutions
Submissions
Nth Fibonacci (iterative)
Medium
Java
Control Flow
25 views
Explanation
Complexity
Problem Statement
Task: return nth Fibonacci number (0-indexed) using iterative loop.
Input Format
An integer n (0-indexed position).
Output Format
The nth Fibonacci number.
Example
Input
7
Output
13
Constraints
• n ≥ 0
• Use iterative loop only (no recursion)
Concept Explanation
Fibonacci sequence (0-indexed):
0, 1, 1, 2, 3, 5, 8, 13, ...
Each number is the sum of the previous two.
Step-by-Step Explanation
1.Read integer n.
2.If n == 0, return 0.
3.If n == 1, return 1.
4.Initialize:
• a = 0 (F(0))
• b = 1 (F(1))
5.Loop from 2 to n:
• c = a + b
• a = b
• b = c
6.After loop ends, return b.
Concept Explanation
Fibonacci sequence (0-indexed):
0, 1, 1, 2, 3, 5, 8, 13, ...
Each number is the sum of the previous two.
Step-by-Step Explanation
1.Read integer n.
2.If n == 0, return 0.
3.If n == 1, return 1.
4.Initialize:
• a = 0 (F(0))
• b = 1 (F(1))
5.Loop from 2 to n:
• c = a + b
• a = b
• b = c
6.After loop ends, return b.
Input / Output Format
Input Format
An integer n (0-indexed position).
Output Format
The nth Fibonacci number.
Constraints
• n ≥ 0
• Use iterative loop only (no recursion)
Examples
Input:
7
Output:
13
Example Solution (Public)
Java
static long fib(int n){long a=0,b=1;for(int i=0;i<n;i++){long t=a+b;a=b;b=t;}return a;}
Official Solution Code
Wrap
Copy
static long fib(int n){long a=0,b=1;for(int i=0;i<n;i++){long t=a+b;a=b;b=t;}return a;}
Please
login
to submit solutions.
Editor
C
C++
Computer Mathematics
CSS
DSA
HTML
Java
JavaScript
NodeJS
PHP
Programming Interview
Python
ReactJS
SQL
Test Cases
Output
Submission Result
Input
7
Expected Output
13
Compile Output
Error
Output
Please
login
to submit solutions.