User Define structure and nested structure.
Define structure and nested structure. Write a program to find out whether the nth term of the Fibonacci series is a prime number or not. Read the value of n from the user and display the result in the main function. Uses separate user-defined function to generate the nth Fibonacci term and to check whether that number is prime or not.
- Structure: A structure is a user-defined data type in C that allows you to combine different data types to define a single type. For example:
struct Person {
char name[50];
int age;
float height;
};
Here, struct Person
is the structure name, and name
, age
, and height
are its members.
- Nested Structure: A nested structure is a structure that is a member of another structure. For example:
struct Address {
char city[50];
char street[50];
};
struct Person {
char name[50];
int age;
struct Address address;
};
Here, struct Address
is nested within struct Person
.
Now, let's write a program to find out whether the nth term of the Fibonacci series is a prime number or not:
#include <stdio.h>
// Function to generate the nth Fibonacci term
int fibonacci(int n) {
if (n <= 1)
return n;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}
// Function to check whether a number is prime
int isPrime(int num) {
if (num <= 1)
return 0; // Not prime
for (int i = 2; i * i <= num; i++) {
if (num % i == 0)
return 0; // Not prime
}
return 1; // Prime
}
int main() {
int n, fib;
// Input value of n
printf("Enter the value of n: ");
scanf("%d", &n);
// Generate the nth Fibonacci term
fib = fibonacci(n);
// Check whether the nth Fibonacci term is prime or not
if (isPrime(fib))
printf("%dth Fibonacci term (%d) is a prime number.\n", n, fib);
else
printf("%dth Fibonacci term (%d) is not a prime number.\n", n, fib);
return 0;
}
This program defines two functions: fibonacci()
to generate the nth Fibonacci term and isPrime()
to check whether a number is prime. Then, it takes input for the value of n from the user, generates the nth Fibonacci term, checks if it's prime or not, and displays the result.
Post a Comment