0% found this document useful (0 votes)
38 views43 pages

Answer Key of XII

The document contains multiple C programming exercises that cover various topics such as recursion, prime number checking, reversing integers, calculating factorials, generating Fibonacci series, finding GCD, and implementing a basic calculator. Each exercise includes a complete code example and a brief description of its functionality. The programs demonstrate fundamental programming concepts and algorithms in C.

Uploaded by

Prabhu Pd. Sah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views43 pages

Answer Key of XII

The document contains multiple C programming exercises that cover various topics such as recursion, prime number checking, reversing integers, calculating factorials, generating Fibonacci series, finding GCD, and implementing a basic calculator. Each exercise includes a complete code example and a brief description of its functionality. The programs demonstrate fundamental programming concepts and algorithms in C.

Uploaded by

Prabhu Pd. Sah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 43

Exercise Solution:

1. Write a program to find the factorial of a given number using recursion.

#include <stdio.h>
// Function to calculate factorial using recursion
unsigned long long factorial(int n) {
// Base case: factorial of 0 is 1
if (n == 0)
return 1;
// Recursive case: factorial(n) = n * factorial(n-1)
else
return n * factorial(n - 1);
}

int main() {
int num;
unsigned long long fact;
printf("Enter a positive integer: ");
scanf("%d", &num);
if (num < 0)
printf("Factorial of a negative number is not defined.\n");
else {
fact = factorial(num);
printf("Factorial of %d = %llu\n", num, fact);
}
return 0;
}
2. Write a program to check whether a given number is prime or not.
#include <stdio.h>

// Function to check whether a number is prime or not

int isPrime(int num) {

int i;

// 0 and 1 are not prime numbers

if (num <= 1)
return 0;

// Check divisibility from 2 to square root of the number

for (i = 2; i * i <= num; i++) {

if (num % i == 0)

return 0; // Not a prime number

return 1; // Prime number

int main() {

int num;

printf("Enter a positive integer: ");

scanf("%d", &num);

// Check if the number is prime or not

if (isPrime(num))

printf("%d is a prime number.\n", num);

else

printf("%d is not a prime number.\n", num);

return 0;

}
3. Write a program to reverse a given integer number.
#include <stdio.h>

// Function to reverse a given integer number

int reverseNumber(int num) {

int reversed = 0;

// Reversing the digits of the number

while (num != 0) {

int digit = num % 10;

reversed = reversed * 10 + digit;

num /= 10;

return reversed;

int main() {

int num, reversedNum;

printf("Enter an integer: ");

scanf("%d", &num);

// Call function to reverse the number

reversedNum = reverseNumber(num);
printf("Reversed number: %d\n", reversedNum);

return 0;

4. Write a C program to compute the sum of the digits of a given integer number.
#include <stdio.h>

// Function to compute the sum of digits of a given integer number

int sumOfDigits(int num) {

int sum = 0;

// Compute the sum of digits

while (num != 0) {

sum += num % 10;

num /= 10;

return sum;

int main() {

int num, sum;

printf("Enter an integer: ");

scanf("%d", &num);
// Call function to compute sum of digits

sum = sumOfDigits(num);

printf("Sum of digits: %d\n", sum);

return 0;

5. Develop a program to print Fibonacci series up to a given number of terms.

#include <stdio.h>

// Function to print Fibonacci series up to n terms


void fibonacciSeries(int n) {
int first = 0, second = 1, next, i;

printf("Fibonacci Series up to %d terms: ", n);

for (i = 1; i <= n; ++i) {


printf("%d, ", first);
next = first + second;
first = second;
second = next;
}
}

int main() {
int numTerms;

printf("Enter the number of terms for Fibonacci series: ");


scanf("%d", &numTerms);

fibonacciSeries(numTerms);

return 0;
}
6. Write a program to find the greatest common divisor (GCD) of two numbers using
Euclid's algorithm.
#include <stdio.h>

// Function to find the greatest common divisor (GCD) using Euclid's algorithm

int gcd(int a, int b) {

int temp;

while (b != 0) {

temp = b;

b = a % b;

a = temp;

return a;

int main() {

int num1, num2;

printf("Enter two integers: ");

scanf("%d %d", &num1, &num2);

// Ensure both numbers are positive

if (num1 < 0 || num2 < 0) {

printf("Please enter positive integers only.\n");

return 1;

}
// Call function to find GCD

int result = gcd(num1, num2);

printf("Greatest Common Divisor (GCD) of %d and %d is: %d\n", num1, num2, result);

return 0;

7. Write a C program to generate Pascal's triangle up to a specified number of rows.

#include <stdio.h>

// Function to generate Pascal's triangle up to n rows


void generatePascalsTriangle(int n) {
int coef = 1, space, i, j;

printf("Pascal's Triangle up to %d rows:\n", n);

for (i = 0; i < n; i++) {


// Printing spaces for formatting
for (space = 1; space <= n - i; space++)
printf(" ");

for (j = 0; j <= i; j++) {


if (j == 0 || i == 0)
coef = 1;
else
coef = coef * (i - j + 1) / j;

printf("%4d", coef);
}
printf("\n");
}
}

int main() {
int numRows;

printf("Enter the number of rows for Pascal's triangle: ");


scanf("%d", &numRows);

generatePascalsTriangle(numRows);

return 0;
}
8. Develop a program to compute the sum of series 1/1! + 1/2! + 1/3! + ... + 1/n!

#include <stdio.h>

// Function to calculate factorial


unsigned long long factorial(int n) {
if (n == 0 || n == 1)
return 1;
else
return n * factorial(n - 1);
}

// Function to compute the sum of series


double sumOfSeries(int n) {
double sum = 0;
for (int i = 1; i <= n; i++) {
sum += 1.0 / factorial(i);
}
return sum;
}

int main() {
int n;

printf("Enter the value of n: ");


scanf("%d", &n);

if (n < 0) {
printf("Please enter a non-negative integer.\n");
return 1;
}

double result = sumOfSeries(n);

printf("Sum of the series up to %d terms: %lf\n", n, result);

return 0;
}
9. Write a program to find the roots of a quadratic equation given the coefficients a, b, and
c.

#include <stdio.h>
#include <math.h>

// Function to find the roots of a quadratic equation


void findRoots(double a, double b, double c) {
double discriminant, root1, root2;

// Calculate discriminant
discriminant = b * b - 4 * a * c;

// Real and distinct roots


if (discriminant > 0) {
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("Roots are real and distinct:\n");
printf("Root 1 = %.2lf\n", root1);
printf("Root 2 = %.2lf\n", root2);
}
// Real and equal roots
else if (discriminant == 0) {
root1 = root2 = -b / (2 * a);
printf("Roots are real and equal:\n");
printf("Root 1 = Root 2 = %.2lf\n", root1);
}
// Imaginary roots
else {
double realPart = -b / (2 * a);
double imaginaryPart = sqrt(-discriminant) / (2 * a);
printf("Roots are complex and imaginary:\n");
printf("Root 1 = %.2lf + %.2lfi\n", realPart, imaginaryPart);
printf("Root 2 = %.2lf - %.2lfi\n", realPart, imaginaryPart);
}
}

int main() {
double a, b, c;

printf("Enter coefficients a, b, and c of the quadratic equation (ax^2 + bx + c): ");


scanf("%lf %lf %lf", &a, &b, &c);
if (a == 0) {
printf("The coefficient 'a' must not be zero for a quadratic equation.\n");
return 1;
}

findRoots(a, b, c);

return 0;
}
10. Write a program to sort an array of integers in ascending order using bubble sort.
#include <stdio.h>

// Function to perform bubble sort

void bubbleSort(int array[], int size) {

int i, j, temp;

for (i = 0; i < size - 1; i++) {

// Last i elements are already in place

for (j = 0; j < size - i - 1; j++) {

// Swap adjacent elements if they are in the wrong order

if (array[j] > array[j + 1]) {

temp = array[j];

array[j] = array[j + 1];

array[j + 1] = temp;

}
int main() {

int array[] = {64, 34, 25, 12, 22, 11, 90};

int size = sizeof(array) / sizeof(array[0]);

int i;

printf("Array before sorting:\n");

for (i = 0; i < size; i++) {

printf("%d ", array[i]);

printf("\n");

// Call bubble sort function

bubbleSort(array, size);

printf("Array after sorting in ascending order:\n");

for (i = 0; i < size; i++) {

printf("%d ", array[i]);

printf("\n");

return 0;

11. Write a program to implement a basic calculator that can perform addition, subtraction,
multiplication, and division operations on two numbers.
#include <stdio.h>
int main() {

char operator;

double num1, num2, result;

printf("Enter an operator (+, -, *, /): ");

scanf(" %c", &operator);

printf("Enter two numbers: ");

scanf("%lf %lf", &num1, &num2);

switch (operator) {

case '+':

result = num1 + num2;

printf("Result: %.2lf + %.2lf = %.2lf\n", num1, num2, result);

break;

case '-':

result = num1 - num2;

printf("Result: %.2lf - %.2lf = %.2lf\n", num1, num2, result);

break;

case '*':

result = num1 * num2;

printf("Result: %.2lf * %.2lf = %.2lf\n", num1, num2, result);

break;

case '/':
if (num2 == 0) {

printf("Error! Division by zero is not allowed.\n");

} else {

result = num1 / num2;

printf("Result: %.2lf / %.2lf = %.2lf\n", num1, num2, result);

break;

default:

printf("Invalid operator!\n");

return 0;

12. Write a C program to convert a given decimal number to binary, octal, and hexadecimal
formats.
#include <stdio.h>

// Function to convert decimal to binary

void decimalToBinary(int num) {

int binary[32], i = 0;

// Convert decimal to binary

while (num > 0) {

binary[i] = num % 2;

num /= 2;

i++;
}

printf("Binary equivalent: ");

// Print binary in reverse order

for (int j = i - 1; j >= 0; j--) {

printf("%d", binary[j]);

printf("\n");

// Function to convert decimal to octal

void decimalToOctal(int num) {

int octal[32], i = 0;

// Convert decimal to octal

while (num > 0) {

octal[i] = num % 8;

num /= 8;

i++;

printf("Octal equivalent: ");

// Print octal in reverse order

for (int j = i - 1; j >= 0; j--) {

printf("%d", octal[j]);
}

printf("\n");

// Function to convert decimal to hexadecimal

void decimalToHexadecimal(int num) {

char hexadecimal[32];

int i = 0, remainder;

// Convert decimal to hexadecimal

while (num > 0) {

remainder = num % 16;

if (remainder < 10)

hexadecimal[i] = remainder + '0';

else

hexadecimal[i] = remainder + 'A' - 10;

num /= 16;

i++;

printf("Hexadecimal equivalent: ");

// Print hexadecimal in reverse order

for (int j = i - 1; j >= 0; j--) {

printf("%c", hexadecimal[j]);

}
printf("\n");

int main() {

int num;

printf("Enter a decimal number: ");

scanf("%d", &num);

if (num < 0) {

printf("Please enter a non-negative integer.\n");

return 1;

decimalToBinary(num);

decimalToOctal(num);

decimalToHexadecimal(num);

return 0;

13. Write a program to count the occurrences of a specific character in a given string.
#include <stdio.h>

// Function to count occurrences of a specific character in a string

int countOccurrences(char *str, char ch) {


int count = 0;

// Iterate through the string

while (*str != '\0') {

// If the current character matches the specified character, increment count

if (*str == ch)

count++;

str++;

return count;

int main() {

char str[100];

char ch;

printf("Enter a string: ");

fgets(str, sizeof(str), stdin);

printf("Enter the character to count occurrences: ");

scanf("%c", &ch);

// Call function to count occurrences

int occurrences = countOccurrences(str, ch);


printf("Occurrences of '%c' in the string: %d\n", ch, occurrences);

return 0;

14. Write a program to check whether a given string is a palindrome or not.


#include <stdio.h>

#include <string.h>

#include <ctype.h>

// Function to check if a string is a palindrome

int isPalindrome(char *str) {

int i, j;

int length = strlen(str);

// Convert the string to lowercase

for (i = 0; i < length; i++) {

str[i] = tolower(str[i]);

// Check if the string is a palindrome

for (i = 0, j = length - 1; i < j; i++, j--) {

// Skip non-alphanumeric characters

while (!isalnum(str[i]) && i < j) {

i++;
}

while (!isalnum(str[j]) && i < j) {

j--;

if (str[i] != str[j]) {

return 0; // Not a palindrome

return 1; // Palindrome

int main() {

char str[100];

printf("Enter a string: ");

fgets(str, sizeof(str), stdin);

// Remove newline character from fgets

if (str[strlen(str) - 1] == '\n') {

str[strlen(str) - 1] = '\0';

// Check if the string is a palindrome

if (isPalindrome(str)) {

printf("The string is a palindrome.\n");


} else {

printf("The string is not a palindrome.\n");

return 0;

15. Write a program that use for and while loop to store 10 elements in a single dimensional
array in C programming and display the result.
#include <stdio.h>

int main() {

int array[10];

int i = 0;

// Using a for loop to store elements in the array

printf("Enter 10 elements:\n");

for (i = 0; i < 10; i++) {

printf("Enter element %d: ", i + 1);

scanf("%d", &array[i]);

// Displaying the elements using a while loop

printf("Elements stored in the array:\n");

i = 0;

while (i < 10) {

printf("%d ", array[i]);


i++;

printf("\n");

return 0;

16. Write a program to Store 10 alphabets in a character type array and display them
sequentially.

#include <stdio.h>

int main() {

char alphabets[10];

int i;

// Storing 10 alphabets in the array

printf("Enter 10 alphabets:\n");

for (i = 0; i < 10; i++) {

printf("Enter alphabet %d: ", i + 1);

scanf(" %c", &alphabets[i]); // Note the space before %c to consume the newline character

// Displaying the alphabets sequentially

printf("Alphabets stored in the array:\n");

for (i = 0; i < 10; i++) {

printf("%c ", alphabets[i]);


}

printf("\n");

return 0;

17. Write a program to find the largest and smallest elements in an array.
#include <stdio.h>

int main() {

int array[100], size, i;

int smallest, largest;

printf("Enter the number of elements in the array: ");

scanf("%d", &size);

// Input array elements

printf("Enter %d elements:\n", size);

for (i = 0; i < size; i++) {

printf("Enter element %d: ", i + 1);

scanf("%d", &array[i]);

// Assume the first element as the smallest and largest initially

smallest = largest = array[0];


// Finding the smallest and largest elements in the array

for (i = 1; i < size; i++) {

if (array[i] < smallest)

smallest = array[i];

if (array[i] > largest)

largest = array[i];

// Display the smallest and largest elements

printf("Smallest element in the array: %d\n", smallest);

printf("Largest element in the array: %d\n", largest);

return 0;

18. Write a program to create two dimensional array of 2x3 size, take integer input and
display them in matrix form.
#include <stdio.h>

int main() {

int matrix[2][3]; // 2x3 matrix

int i, j;

// Input elements into the matrix

printf("Enter elements for a 2x3 matrix:\n");

for (i = 0; i < 2; i++) {

for (j = 0; j < 3; j++) {


printf("Enter element at position (%d, %d): ", i + 1, j + 1);

scanf("%d", &matrix[i][j]);

// Display the matrix

printf("Matrix form:\n");

for (i = 0; i < 2; i++) {

for (j = 0; j < 3; j++) {

printf("%d ", matrix[i][j]);

printf("\n");

return 0;

19. Write a program to find the addition of 2x2 matrix and display their result.

#include <stdio.h>

int main() {

int matrix1[2][2], matrix2[2][2], result[2][2];

int i, j;

// Input elements for first matrix


printf("Enter elements for the first 2x2 matrix:\n");

for (i = 0; i < 2; i++) {

for (j = 0; j < 2; j++) {

printf("Enter element at position (%d, %d): ", i + 1, j + 1);

scanf("%d", &matrix1[i][j]);

// Input elements for second matrix

printf("Enter elements for the second 2x2 matrix:\n");

for (i = 0; i < 2; i++) {

for (j = 0; j < 2; j++) {

printf("Enter element at position (%d, %d): ", i + 1, j + 1);

scanf("%d", &matrix2[i][j]);

// Perform matrix addition

for (i = 0; i < 2; i++) {

for (j = 0; j < 2; j++) {

result[i][j] = matrix1[i][j] + matrix2[i][j];

// Display the result matrix


printf("Result of matrix addition:\n");

for (i = 0; i < 2; i++) {

for (j = 0; j < 2; j++) {

printf("%d ", result[i][j]);

printf("\n");

return 0;

20. Use structure to store the basic information of a student and display them on screen.
#include <stdio.h>

// Define a structure to store student information

struct Student {

char name[50];

int age;

long int rollNumber;

float marks;

};

int main() {

// Declare a variable of type struct Student

struct Student student;


// Input student information

printf("Enter student information:\n");

printf("Name: ");

scanf("%s", student.name); // Assuming name doesn't contain spaces

printf("Age: ");

scanf("%d", &student.age);

printf("Roll Number: ");

scanf("%ld", &student.rollNumber);

printf("Marks: ");

scanf("%f", &student.marks);

// Display student information

printf("\nStudent Information:\n");

printf("Name: %s\n", student.name);

printf("Age: %d\n", student.age);

printf("Roll Number: %ld\n", student.rollNumber);

printf("Marks: %.2f\n", student.marks);

return 0;

21. Write a program to perform basic file operations like reading from a file, writing to a file,
and copying files.
#include <stdio.h>

#include <stdlib.h>

#define MAX_FILENAME_LENGTH 100


#define BUFFER_SIZE 1024

// Function to read content from a file and display it

void readFile(char *filename) {

FILE *file = fopen(filename, "r");

if (file == NULL) {

printf("Error opening file for reading.\n");

return;

char buffer[BUFFER_SIZE];

printf("Contents of the file '%s':\n", filename);

while (fgets(buffer, BUFFER_SIZE, file) != NULL) {

printf("%s", buffer);

fclose(file);

// Function to write content to a file

void writeFile(char *filename, char *content) {

FILE *file = fopen(filename, "w");

if (file == NULL) {

printf("Error opening file for writing.\n");

return;
}

fputs(content, file);

printf("Content successfully written to the file '%s'.\n", filename);

fclose(file);

// Function to copy content from one file to another

void copyFile(char *sourceFilename, char *destinationFilename) {

FILE *sourceFile = fopen(sourceFilename, "r");

if (sourceFile == NULL) {

printf("Error opening source file for reading.\n");

return;

FILE *destinationFile = fopen(destinationFilename, "w");

if (destinationFile == NULL) {

printf("Error opening destination file for writing.\n");

fclose(sourceFile);

return;

char buffer[BUFFER_SIZE];
size_t bytesRead;

while ((bytesRead = fread(buffer, 1, BUFFER_SIZE, sourceFile)) > 0) {

fwrite(buffer, 1, bytesRead, destinationFile);

printf("File '%s' successfully copied to '%s'.\n", sourceFilename, destinationFilename);

fclose(sourceFile);

fclose(destinationFile);

int main() {

char sourceFilename[MAX_FILENAME_LENGTH];

char destinationFilename[MAX_FILENAME_LENGTH];

char content[BUFFER_SIZE];

printf("Enter the name of the source file: ");

scanf("%s", sourceFilename);

printf("Enter the name of the destination file: ");

scanf("%s", destinationFilename);

printf("Enter content to write to the destination file:\n");

getchar(); // Consume the newline character left in the input buffer

fgets(content, BUFFER_SIZE, stdin);


readFile(sourceFilename);

writeFile(destinationFilename, content);

copyFile(sourceFilename, "copy_of_file.txt");

return 0;

22. Write a program to implement structure and file handling in C to store information of 10
employees of a school and print them in proper format.
#include <stdio.h>

#include <stdlib.h>

#define MAX_NAME_LENGTH 50

// Define a structure to store employee information

struct Employee {

char name[MAX_NAME_LENGTH];

int age;

long int employeeID;

float salary;

};

// Function to input employee information

void inputEmployee(struct Employee *employee) {

printf("Enter employee name: ");

scanf("%s", employee->name);
printf("Enter employee age: ");

scanf("%d", &employee->age);

printf("Enter employee ID: ");

scanf("%ld", &employee->employeeID);

printf("Enter employee salary: ");

scanf("%f", &employee->salary);

// Function to print employee information

void printEmployee(struct Employee employee) {

printf("Employee Name: %s\n", employee.name);

printf("Employee Age: %d\n", employee.age);

printf("Employee ID: %ld\n", employee.employeeID);

printf("Employee Salary: %.2f\n", employee.salary);

int main() {

// Declare an array of 10 Employee structures

struct Employee employees[10];

// Input information for 10 employees

printf("Enter information for 10 employees:\n");

for (int i = 0; i < 10; i++) {

printf("Enter details for Employee %d:\n", i + 1);

inputEmployee(&employees[i]);
}

// Open a file for writing

FILE *file = fopen("employee_info.txt", "w");

if (file == NULL) {

printf("Error opening file for writing.\n");

return 1;

// Write employee information to the file

fprintf(file, "Employee Information:\n");

for (int i = 0; i < 10; i++) {

fprintf(file, "Employee %d:\n", i + 1);

fprintf(file, "Name: %s\n", employees[i].name);

fprintf(file, "Age: %d\n", employees[i].age);

fprintf(file, "ID: %ld\n", employees[i].employeeID);

fprintf(file, "Salary: %.2f\n", employees[i].salary);

fprintf(file, "\n");

// Close the file

fclose(file);

// Print employee information from the array

printf("\nEmployee Information:\n");
for (int i = 0; i < 10; i++) {

printf("Employee %d:\n", i + 1);

printEmployee(employees[i]);

printf("\n");

printf("Employee information has been saved to 'employee_info.txt'.\n");

return 0;

23. Write a program to perform subtraction, multiplication, and transpose operations.


#include <stdio.h>

#define ROWS 3

#define COLS 3

// Function to perform subtraction of two matrices

void subtractMatrices(int mat1[][COLS], int mat2[][COLS], int result[][COLS]) {

for (int i = 0; i < ROWS; i++) {

for (int j = 0; j < COLS; j++) {

result[i][j] = mat1[i][j] - mat2[i][j];

}
// Function to perform multiplication of two matrices

void multiplyMatrices(int mat1[][COLS], int mat2[][COLS], int result[][COLS]) {

for (int i = 0; i < ROWS; i++) {

for (int j = 0; j < COLS; j++) {

result[i][j] = 0;

for (int k = 0; k < COLS; k++) {

result[i][j] += mat1[i][k] * mat2[k][j];

// Function to calculate transpose of a matrix

void transposeMatrix(int mat[][COLS], int transpose[][ROWS]) {

for (int i = 0; i < ROWS; i++) {

for (int j = 0; j < COLS; j++) {

transpose[j][i] = mat[i][j];

// Function to display a matrix

void displayMatrix(int mat[][COLS]) {

for (int i = 0; i < ROWS; i++) {

for (int j = 0; j < COLS; j++) {


printf("%d ", mat[i][j]);

printf("\n");

printf("\n");

int main() {

int matrix1[ROWS][COLS] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

int matrix2[ROWS][COLS] = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};

int result[ROWS][COLS];

int transpose[COLS][ROWS];

// Subtract matrices

subtractMatrices(matrix1, matrix2, result);

printf("Subtraction Result:\n");

displayMatrix(result);

// Multiply matrices

multiplyMatrices(matrix1, matrix2, result);

printf("Multiplication Result:\n");

displayMatrix(result);

// Transpose matrix

transposeMatrix(matrix1, transpose);
printf("Transpose of Matrix 1:\n");

displayMatrix(transpose);

return 0;

}
a. Write a C program to find the factorial of a number by using function
#include <stdio.h>
// Function to calculate factorial
int factorial(int n) {
if (n == 0 || n == 1)
return 1;
else
return n * factorial(n - 1);
}
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("Factorial of %d is %d\n", num, factorial(num));
return 0;
}

b. Write a C program to check whether a given number is a prime number or not by using
functions.
#include <stdio.h>
#include <stdbool.h>
// Function to check prime number
bool isPrime(int n) {
if (n <= 1)
return false;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0)
return false;
}
return true;
}
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (isPrime(num))
printf("%d is a prime number\n", num);
else
printf("%d is not a prime number\n", num);
return 0;
}

c. Write a C program to find the sum of digits of a number.


#include <stdio.h>
// Function to compute sum of digits
int sumOfDigits(int n) {
int sum = 0;
while (n != 0) {
sum += n % 10;
n /= 10;
}
return sum;
}
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("Sum of digits of %d is %d\n", num, sumOfDigits(num));
return 0;
}

d. Write a C program to find the Fibonacci number up to given terms by using functions
#include <stdio.h>

// Function to print Fibonacci series


void fibonacci(int n) {
int a = 0, b = 1, c;
printf("Fibonacci Series up to %d terms: ", n);
printf("%d %d ", a, b);
for (int i = 3; i <= n; i++) {
c = a + b;
printf("%d ", c);
a = b;
b = c;
}
printf("\n");
}
int main() {
int num;
printf("Enter the number of terms: ");
scanf("%d", &num);
fibonacci(num);
return 0;
}

e. Write a C program to calculate exponent or power of a given number by using function.


#include <stdio.h>

// Function to calculate power


double power(double base, int exponent) {
if (exponent == 0)
return 1;
else if (exponent > 0)
return base * power(base, exponent - 1);
else
return (1 / base) * power(base, exponent + 1);
}

int main() {
double base;
int exponent;
printf("Enter base: ");
scanf("%lf", &base);
printf("Enter exponent: ");
scanf("%d", &exponent);
printf("%.2lf raised to the power %d is %.2lf\n", base, exponent, power(base,
exponent));
return 0;
}

f. Write a C program that generates the Fibonacci series up to a given number using recursion
function.
#include <stdio.h>

int fibonacci(int n) {
if (n <= 1)
return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}

int main() {
int n, i;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci series: ");
for (i = 0; i < n; i++) {
printf("%d ", fibonacci(i));
}
return 0;
}

g. Write a C program that calculates the factorial of a given number using recursion
function.
#include <stdio.h>

int factorial(int n) {
if (n == 0)
return 1;
return n * factorial(n - 1);
}

int main() {
int n;
printf("Enter a non-negative integer: ");
scanf("%d", &n);
if (n < 0) {
printf("Error: Factorial is not defined for negative numbers.\n");
} else {
printf("Factorial of %d = %d\n", n, factorial(n));
}
return 0;
}

You might also like