Loop Assignment 27 β€” Generate First N Terms of the Tribonacci Sequence Using While Loop
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Generate the First N Terms of the Tribonacci Sequence Using a While Loop

πŸ“‘ On this page:
  • What Is the Tribonacci Sequence?
  • The Sliding-Window Algorithm
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
πŸ“š In this program, you will learn:
  • How the Tribonacci sequence generalizes Fibonacci: each term is the sum of the previous three
  • Why a = b; b = c; c = next; is the correct rotation order β€” and what happens if you do it wrong
  • Why a three-variable sliding window is enough, with no array needed
  • Why the sequence is O(N) in time and O(1) in space
  • How to generalize the pattern to a k-step recurrence (Tetranacci, Pentanacci, …)

What Is the Tribonacci Sequence?

The Fibonacci sequence is defined by a simple rule: each term is the sum of the previous two. The Tribonacci sequence is the natural generalization: each term is the sum of the previous three. The standard seed values are 0, 0, 1, giving the sequence 0, 0, 1, 1, 2, 4, 7, 13, 24, 44, 81, 149, …. Some textbooks use 0, 1, 1 as seeds, which produces a different (but still valid) sequence β€” the choice is a convention, and both are widely used.

The recurrence relation is T(n) = T(n-1) + T(n-2) + T(n-3) for n β‰₯ 3, with the seeds T(0) = 0, T(1) = 0, T(2) = 1. Unlike Fibonacci, whose closed form involves the golden ratio, Tribonacci's closed form involves the real root of xΒ³ = xΒ² + x + 1, approximately 1.839286 β€” called the Tribonacci constant. The sequence grows roughly like 1.839ⁿ, which is slower than Fibonacci's 1.618ⁿ but still exponentially fast.

What makes Tribonacci a good loop exercise is the need for three sliding variables, not two. Fibonacci is a two-variable dance; Tribonacci is a three-variable dance, and the rotation order matters. Get the order wrong and you'll overwrite a variable before using it, producing a totally different sequence. That's the small trap in this program.

πŸ’‘ In one line: maintain three variables a, b, c; each iteration prints c, computes next = a + b + c, then rotates a = b, b = c, c = next.

Diagram showing the Tribonacci recurrence T(n) = T(n-1) + T(n-2) + T(n-3) with the first terms 0, 0, 1, 1, 2, 4, 7, 13, 24 and arrows showing which previous terms sum to each new term

The Sliding-Window Algorithm

In pseudocode, the whole thing is a single while loop:

a = 0; b = 0; c = 1; i = 0
while i < N:
    print c
    next = a + b + c
    a = b; b = c; c = next
    i = i + 1
                                

That's the whole algorithm. The three variables a, b, c form a sliding window over the last three terms. Each iteration, the window moves forward by one β€” the oldest term (a) is dropped, and the new term (next) becomes c. The sequence is printed as it's generated, so no array is needed. Space complexity: O(1).

Iteration a b c Printed next = a+b+c
start001β€”β€”
100111
201112
311224
412447
5247713
647131324
7713242444
81324444481
924448181149

The sequence printed is 1, 1, 2, 4, 7, 13, 24, 44, 81, 149, … for N = 10. (Some conventions print 0, 0, 1, 1, 2, 4, … starting from the seeds. The variant below prints from the first seed, which includes the two zeros. Both are correct β€” the choice is a convention.)

Complete C Program

Program: generate the first N Tribonacci numbers using a while loop

#include <stdio.h>

int main(void) {
    int n;
    printf("Enter the number of terms (N): ");
    if (scanf("%d", &n) != 1 || n < 1) {
        printf("Invalid input. Enter a positive integer.\n");
        return 1;
    }

    long long a = 0, b = 0, c = 1;   /* seeds: 0, 0, 1 */
    int i = 0;

    printf("Tribonacci sequence (first %d terms):\n", n);
    while (i < n) {
        printf("%lld ", c);
        long long next = a + b + c;
        a = b;
        b = c;
        c = next;
        i++;
    }
    printf("\n");
    return 0;
}
                                    

And here's a variant that prints all three seeds first, matching the canonical sequence 0, 0, 1, 1, 2, 4, 7, … more explicitly:

Variant printing from the very first seed

#include <stdio.h>

int main(void) {
    int n;
    printf("Enter N: ");
    scanf("%d", &n);

    long long a = 0, b = 0, c = 1;
    printf("0 0 1 ");
    int count = 3;   /* we've already printed three terms */
    while (count < n) {
        long long next = a + b + c;
        printf("%lld ", next);
        a = b;
        b = c;
        c = next;
        count++;
    }
    printf("\n");
    return 0;
}
                                    

The first version is the cleaner one to submit β€” the loop structure is uniform, and the interpretation "print the term, then advance" is clear. The second version handles the seeds explicitly and is useful if the assignment expects the sequence to start exactly at 0.

Program Output

Enter the number of terms (N): 10
Tribonacci sequence (first 10 terms):
1 1 2 4 7 13 24 44 81 149
                                

With the seed-printing variant, the same N = 10 produces:

0 0 1 1 2 4 7 13 24 44
                                

Both are valid Tribonacci sequences β€” the only difference is where you stop. The canonical OEIS sequence A000073 starts 0, 0, 1, 1, 2, 4, 7, 13, 24, 44, …. Input N = 1 should produce a single term. Input N = 3 gives the seeds 0, 0, 1 (or 1, 1, 2 with the simpler variant).

Step-by-Step Explanation

Let's walk through the simpler variant for N = 6, watching the three variables rotate.

1. Reading and validating input

scanf("%d", &n) reads N. The validation n < 1 rejects zero and negatives because the sequence always has at least one term. There's no upper bound enforced, but long long overflows around N = 60 (the Tribonacci growth rate of 1.839ⁿ reaches 2⁢³ in about 60 terms). For safety, you could cap N at 60.

2. The seed values

a = 0, b = 0, c = 1. These are the first three Tribonacci numbers in the standard convention. They're initialized before the loop, and they're the state the loop depends on. The variable c holds the "current" term β€” the one about to be printed β€” and a and b hold the two that came before it.

3. The rotation order β€” the only subtle point

Inside the loop body, the order is critical:

  1. next = a + b + c; β€” compute the next term, using all three variables while they still hold their correct values.
  2. a = b; β€” shift the oldest term out, the middle term becomes the oldest.
  3. b = c; β€” the current term becomes the middle term.
  4. c = next; β€” the newly computed term becomes the current term.

If you reverse the order β€” say c = next; b = c; a = b; β€” then after the first assignment c already holds the new value, so b = c copies the new value instead of the old one, and a = b copies that, and you lose the whole history. The result is a completely different (and wrong) sequence. The order a = b; b = c; c = next; is correct precisely because each assignment uses the value from before the previous assignment, and none of the right-hand sides depend on a variable that was just overwritten.

4. Watching N = 6

Starting state: a = 0, b = 0, c = 1.

  1. Iteration 1: print 1; next = 0 + 0 + 1 = 1; rotate to a = 0, b = 1, c = 1.
  2. Iteration 2: print 1; next = 0 + 1 + 1 = 2; rotate to a = 1, b = 1, c = 2.
  3. Iteration 3: print 2; next = 1 + 1 + 2 = 4; rotate to a = 1, b = 2, c = 4.
  4. Iteration 4: print 4; next = 1 + 2 + 4 = 7; rotate to a = 2, b = 4, c = 7.
  5. Iteration 5: print 7; next = 2 + 4 + 7 = 13; rotate to a = 4, b = 7, c = 13.
  6. Iteration 6: print 13; next = 4 + 7 + 13 = 24; rotate to a = 7, b = 13, c = 24.
  7. i = 6, condition i < 6 false β€” loop exits.

Printed: 1 1 2 4 7 13. That matches the first six terms starting from c = 1. Note the pattern of rotations β€” the entire state shifts one slot to the left, and the new term enters at c. It's the same operation as a queue, just implemented with three named variables.

5. Why O(N) time and O(1) space

The loop runs N times, and each iteration does constant work β€” three additions, three assignments, one printf. Total time: O(N). The variables used are a, b, c, next, i β€” a fixed set, regardless of N. Total space: O(1). This is strictly better than storing all N terms in an array (O(N) space), which would be necessary if you needed random access to a specific term, but is wasteful for pure sequential output.

6. Why the variable type must be long long

The Tribonacci sequence grows at about 1.839ⁿ. At N = 40, the value is around 1.4 Γ— 10⁹ (fits in 32-bit int). At N = 50, it's around 4.5 Γ— 10ΒΉΒΉ (exceeds int). At N = 60, it's around 8 Γ— 10¹⁴ (fits in long long). At N = 80, it overflows 64-bit entirely. So long long covers N up to about 60; use unsigned long long for a bit more range, or a bignum library beyond that.

7. Generalizing to k-step recurrences

The same pattern extends to any k-step recurrence β€” Tetranacci (sum of last four), Pentanacci (sum of last five), and so on. You just need k variables (or a circular buffer of size k), and the rotation becomes a shift. For k = 4: d = a + b + c + d; a = b; b = c; c = d; β€” wait, that overwrites d before using it. The correct form is next = a + b + c + d; a = b; b = c; c = d; d = next;. Same lesson: compute the new value into a temporary first, then shift.

🎯 Remember this: three variables a, b, c hold the last three terms. Compute next first, then rotate a = b; b = c; c = next; in that order. Print c before rotating to output the term. Use long long for N up to 60.

Frequently Asked Questions

1. Why does the sequence start at 0, 0, 1 and not 0, 1, 1?

Both conventions are used, and the choice is somewhat arbitrary. The OEIS entry for the Tribonacci numbers (A000073) uses 0, 0, 1 as seeds, giving 0, 0, 1, 1, 2, 4, 7, 13, …. Some textbooks use 0, 1, 1 to make the sequence start at 0 without a repeat, giving 0, 1, 1, 2, 4, 7, …. Either is mathematically valid as long as you're consistent; for an assignment, follow whatever the problem statement specifies.

2. Why does the rotation order matter so much?

Because each assignment overwrites a variable that the next assignment uses. If you write a = b; b = c; c = next; in that order, then b = c uses the original c (before it was updated), and a = b uses the original b. If you reverse the order to c = next; b = c; a = b;, then b = c copies the new c (the just-computed next), and a = b copies that β€” losing the original values. The correct pattern is to compute into a temporary, then shift from oldest to newest.

3. Can I use an array instead of three variables?

Yes. An array t[N] with t[0] = 0, t[1] = 0, t[2] = 1 and t[i] = t[i-1] + t[i-2] + t[i-3] for i β‰₯ 3 works just as well. The tradeoff: the array version uses O(N) space but allows random access to any term after the loop finishes. The three-variable version is O(1) space but forgets earlier terms once they rotate out. For the assignment ("generate the first N terms"), the three-variable version is the more elegant solution.

4. What's the difference between Tribonacci and Fibonacci?

Fibonacci: each term is the sum of the previous two. Tribonacci: each term is the sum of the previous three. Fibonacci grows at ~1.618ⁿ (the golden ratio); Tribonacci grows at ~1.839ⁿ (the Tribonacci constant). Both are exponentially fast, but Tribonacci grows faster because it has more terms to sum. Tetranacci (sum of four) grows at ~1.927ⁿ, and Pentanacci (sum of five) at ~1.966ⁿ β€” approaching 2 as k increases.

5. Why use a while loop instead of a for loop?

Either works. The assignment specifies a while loop, and a while loop is natural here because we're tracking a counter that isn't directly the loop variable β€” the loop continues until we've printed N terms, and the term itself changes inside the body. A for loop with for (int i = 0; i < n; i++) would be equally clear. Choose based on what the problem asks for.

6. What if N is very large, like 1000?

The loop still runs N times, so it's fast β€” about 1000 iterations. But the values overflow long long around N = 60, so the printed sequence will be garbage after that. For large N, you'd need a bignum library (like GMP), or output only the last few digits via modular arithmetic. The algorithm's structure doesn't change, but the integer type has to.

πŸ’‘ Tip: After this program, try the Tetranacci sequence (sum of four): a = 0, b = 0, c = 0, d = 1, then next = a + b + c + d; a = b; b = c; c = d; d = next;. Then try the Padovan sequence (each term is the sum of the previous two, skipping one: P(n) = P(n-2) + P(n-3)) β€” it's a good exercise in generalizing the sliding-window idea.

πŸ“– Related Tutorials

  • 25. Sum of the Series 1 + 1/2Β² + 1/3Β² + … + 1/NΒ² Using a For Loop
  • 26. Sum of the Series 1! + 2! + 3! + … + N! Using a For Loop
  • 28. Find the Largest Prime Factor Using a While Loop
  • 29. Iterative Binary Search Using a While Loop
  • 30. Check Amicable Numbers Using a For Loop
  • While Loop
  • C FOR Loop
  • All 30 Loop Assignments

Previous Topic: -->> 26. Sum of the Series 1! + 2! + 3! + … + N! Using a For Loop   ||   Next Topic: -->> 28. Find the Largest Prime Factor Using a While Loop


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.