NBC 103 • Practical #4
Fibonacci Sequence & Prime Number Checker
Aim: To generate N terms of the Fibonacci sequence and determine if a number is Prime using loop constructs.
Step-by-Step Algorithm & Logic
- 11. For Fibonacci: Initialize t1 = 0, t2 = 1. In a loop up to N, print t1, next = t1 + t2, t1 = t2, t2 = next.
- 22. For Prime: Assume isPrime = true for num > 1. Loop from i = 2 up to sqrt(num).
- 33. If (num % i == 0), set isPrime = false and break.
- 44. Display whether number is Prime or Composite.
#include <stdio.h>
#include <stdbool.h>
int main(void) {
int n = 8, num = 29;
long long t1 = 0, t2 = 1, next;
printf("=== Fibonacci Sequence (%d terms) ===\n", n);
for (int i = 1; i <= n; i++) {
printf("%lld ", t1);
next = t1 + t2;
t1 = t2;
t2 = next;
}
printf("\n\n");
printf("=== Prime Number Checker ===\n");
bool isPrime = (num > 1);
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
if (isPrime)
printf("%d is a PRIME number.\n", num);
else
printf("%d is NOT a prime number.\n", num);
return 0;
}Sample Input:
n = 8, num = 29
Sample Output:
Fibonacci: 0 1 1 2 3 5 8 13 29 is a PRIME number.
Practical Exam Viva Questions (Exp #4)
1