UNIT-04
EXPERIMENT-31
Objective: Design a modularized program to check if a given positive
integer number is a circular prime or not?
Theory: A number is a circular prime if every rotation of its digits
(achieved by repeatedly shifting the first digit to the end) produces a number
that is also a prime number, requiring the modularized program to check
primality for the number and all its rotations.
Program:
#include <stdio.h>
#include <math.h> // Required for sqrt() and pow()
int isPrime(int n);
int getNumberOfDigits(int n);
int rotateNumber(int n, int num_digits);
int isCircularPrime(int n);
int isPrime(int n) {
if (n <= 1) {
return 0;
}
if (n <= 3) {
return 1;
}
if (n % 2 == 0 || n % 3 == 0) {
return 0;
}
for (int i = 5; i * i <= n; i = i + 6) {
if (n % i == 0 || n % (i + 2) == 0) {
return 0;
}
}
return 1; // It is prime
}
int getNumberOfDigits(int n) {
if (n == 0) {
return 1;
}
int count = 0;
while (n > 0) {
n /= 10;
count++;
}
return count;
}
int rotateNumber(int n, int num_digits) {
// 1. Get the last digit
int last_digit = n % 10; // e.g., 197 % 10 = 7
// 2. Remove the last digit
int remaining_digits = n / 10; // e.g., 197 / 10 = 19
// 3. Find the power of 10 to shift the last digit
// pow(10, num_digits - 1) gives 10^(3-1) = 100
int shift_power = (int)pow(10, num_digits - 1);
// 4. Construct the new number: (last_digit * shift_power) +
remaining_digits
// (7 * 100) + 19 = 719
int rotated = (last_digit * shift_power) + remaining_digits;
return rotated;
}
int isCircularPrime(int n) {
// A single-digit number is circular prime if it is prime.
if (n < 10) {
return isPrime(n);
}
if (!isPrime(n)) {
return 0; // If the original is not prime, it can't be circular prime.
}
int num_digits = getNumberOfDigits(n);
int current_rotation = n;
for (int i = 1; i < num_digits; i++) {
current_rotation = rotateNumber(current_rotation, num_digits);
if (!isPrime(current_rotation)) {
return 0; // Found a non-prime rotation, so it's not a circular prime.
}
}
return 1;
}
int main() {
int number;
printf("--- Circular Prime Checker ---\n");
printf("Enter a positive integer: ");
if (scanf("%d", &number) != 1 || number <= 0) {
printf("Invalid input. Please enter a positive integer.\n");
return 1;
}
if (isCircularPrime(number)) {
printf("\nRESULT: The number %d IS a Circular Prime.\n", number);
} else {
printf("\nRESULT: The number %d IS NOT a Circular Prime.\n",
number);
}
return 0;
}
Output:
EXPERIMENT-32
Objective: Design a modularized program to compute a maximum of 8
numbers?
Theory: The program employs a modularized approach by using a
dedicated function that iteratively compares each of the 8 numbers
against a running maximum value, returning the final largest value found
after all comparisons are complete.
Program:
#include <stdio.h>
#include <limits.h> // Used for INT_MIN, a safe starting point for max
comparison
/**
* @brief Finds the maximum value in an array of integers.
*
* @param arr The array of integers.
* @param size The number of elements in the array.
* @return The maximum integer found in the array.
*/
int find_maximum(const int arr[], int size) {
// Check if the array is empty
if (size <= 0) {
// Return a very low number or handle error if required.
// For this simple case, we'll return INT_MIN to indicate an issue
// or a maximum that is impossibly low.
return INT_MIN;
}
// Initialize the maximum with the first element of the array
int max = arr[0];
// Iterate through the rest of the array elements
for (int i = 1; i < size; i++) {
if (arr[i] > max) {
max = arr[i]; // Update max if a larger element is found
}
}
return max;
}
int main() {
// 1. Define the 8 numbers. Using an array makes the modular function
generic.
// We can change the numbers here easily without touching the function
logic.
const int num_count = 8;
int numbers[num_count];
int max_result;
printf("--- Maximum Finder for 8 Numbers ---\n");
// 2. Input the 8 numbers from the user
for (int i = 0; i < num_count; i++) {
printf("Enter number %d/%d: ", i + 1, num_count);
// Basic input validation
if (scanf("%d", &numbers[i]) != 1) {
printf("Invalid input. Exiting.\n");
// Clear the input buffer to prevent infinite loops in a real scenario
while(getchar() != '\n');
return 1;
}
}
printf("\nInput sequence: ");
for (int i = 0; i < num_count; i++) {
printf("%d%s", numbers[i], (i == num_count - 1) ? "" : ", ");
}
printf("\n");
// 3. Call the modularized function to find the maximum
max_result = find_maximum(numbers, num_count);
// 4. Display the result
if (max_result != INT_MIN) {
printf("The maximum of the %d numbers is: %d\n", num_count,
max_result);
} else {
printf("Could not calculate the maximum (Input error).\n");
}
return 0;
}
Output:
EXPERIMENT-33
Objective: Design a modular program which reads an array of n integer
elements and outputs mean (average), range (max-min) and mode (most
frequent elements)?
Theory: This modular program focuses on fundamental statistical analysis,
calculating the central tendency (mean), data spread (range), and frequency
(mode) of a given set of integer data.
Program:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <float.h>
// --- MODULAR FUNCTIONS ---
/**
* @brief Finds the maximum value in an array of integers.
*
* @param arr The array of integers.
* @param size The number of elements in the array.
* @return The maximum integer found in the array.
*/
int find_maximum(const int arr[], int size) {
if (size <= 0) {
return INT_MIN;
}
int max = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
/**
* @brief Finds the minimum value in an array of integers.
*
* @param arr The array of integers.
* @param size The number of elements in the array.
* @return The minimum integer found in the array.
*/
int find_minimum(const int arr[], int size) {
if (size <= 0) {
return INT_MAX;
}
int min = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] < min) {
min = arr[i];
}
}
return min;
}
/**
* @brief Calculates the mean (average) of the array elements.
*
* @param arr The array of integers.
* @param size The number of elements in the array.
* @return The mean (average) as a double. Returns DBL_MIN if array is
empty.
*/
double calculate_mean(const int arr[], int size) {
if (size <= 0) {
return DBL_MIN;
}
long long sum = 0; // Use long long for sum to prevent overflow
for (int i = 0; i < size; i++) {
sum += arr[i];
}
// Cast to double for floating-point division
return (double)sum / size;
}
/**
* @brief Finds the mode (most frequent element) of the array.
* NOTE: This simple implementation only finds one mode.
* @param arr The array of integers.
* @param size The number of elements in the array.
* @return The mode value. Returns INT_MIN if array is empty.
*/
int find_mode(const int arr[], int size) {
if (size <= 0) {
return INT_MIN;
}
int mode = arr[0];
int max_count = 0;
for (int i = 0; i < size; i++) {
int current_element = arr[i];
int current_count = 0;
// Count occurrences of the current element
for (int j = 0; j < size; j++) {
if (arr[j] == current_element) {
current_count++;
}
}
// Update mode if the current element is more frequent
if (current_count > max_count) {
max_count = current_count;
mode = current_element;
}
}
// If max_count is 1, every element appeared only once (no clear mode)
// We return the first element as the "mode" or could implement a check
// for actual frequency. For simplicity, we return the most frequent one
found.
return mode;
}
// --- MAIN EXECUTION ---
int main() {
int n;
int *numbers = NULL; // Pointer to the array
int min, max, range, mode;
double mean;
printf("--- Array Analysis Program ---\n");
// 1. Get the number of elements (N) from the user
do {
printf("Enter the number of elements (n > 0): ");
if (scanf("%d", &n) != 1 || n <= 0) {
printf("Invalid input. Please enter a positive integer.\n");
// Clear input buffer
while(getchar() != '\n');
n = 0; // Ensure loop continues
}
} while (n <= 0);
// 2. Dynamically allocate memory for the array
numbers = (int*)malloc(n * sizeof(int));
if (numbers == NULL) {
printf("Memory allocation failed. Exiting.\n");
return 1;
}
// 3. Input the N numbers from the user
printf("\n");
for (int i = 0; i < n; i++) {
printf("Enter element %d/%d: ", i + 1, n);
if (scanf("%d", &numbers[i]) != 1) {
printf("Invalid input. Exiting.\n");
free(numbers); // Free allocated memory before exit
while(getchar() != '\n');
return 1;
}
}
// 4. Calculate Statistics using Modular Functions
printf("\n--- Results ---\n");
// Mean
mean = calculate_mean(numbers, n);
if (mean != DBL_MIN) {
printf("Mean (Average): %.2f\n", mean);
}
// Min and Max (for Range)
max = find_maximum(numbers, n);
min = find_minimum(numbers, n);
if (max != INT_MIN && min != INT_MAX) {
range = max - min;
printf("Maximum: %d\n", max);
printf("Minimum: %d\n", min);
printf("Range (Max - Min): %d\n", range);
}
// Mode
mode = find_mode(numbers, n);
if (mode != INT_MIN) {
printf("Mode (Most Frequent): %d\n", mode);
}
// 5. Free dynamically allocated memory
free(numbers);
return 0;
}
Output:
EXPERIMENT-34
Objective: Design a modular program which reads an array of n integer
elements and outputs median?
Theory: The core function of this modular program is to calculate the
median—the middle value of a dataset—by first sorting the input array of
integers.
Program:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <float.h>
// --- HELPER FUNCTION (For Sorting) ---
/**
* @brief Helper function used by qsort() to compare two integers.
* @param a Pointer to the first integer.
* @param b Pointer to the second integer.
* @return A value < 0 if *a < *b, 0 if *a == *b, and > 0 if *a > *b.
*/
int compare_integers(const void *a, const void *b) {
return (*(const int*)a - *(const int*)b);
}
// --- MODULAR FUNCTIONS ---
/**
* @brief Finds the maximum value in an array of integers.
* @param arr The array of integers.
* @param size The number of elements in the array.
* @return The maximum integer found in the array.
*/
int find_maximum(const int arr[], int size) {
if (size <= 0) {
return INT_MIN;
}
int max = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
/**
* @brief Finds the minimum value in an array of integers.
* @param arr The array of integers.
* @param size The number of elements in the array.
* @return The minimum integer found in the array.
*/
int find_minimum(const int arr[], int size) {
if (size <= 0) {
return INT_MAX;
}
int min = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] < min) {
min = arr[i];
}
}
return min;
}
/**
* @brief Calculates the mean (average) of the array elements.
* @param arr The array of integers.
* @param size The number of elements in the array.
* @return The mean (average) as a double. Returns DBL_MIN if array is
empty.
*/
double calculate_mean(const int arr[], int size) {
if (size <= 0) {
return DBL_MIN;
}
long long sum = 0; // Use long long for sum to prevent overflow
for (int i = 0; i < size; i++) {
sum += arr[i];
}
// Cast to double for floating-point division
return (double)sum / size;
}
/**
* @brief Finds the mode (most frequent element) of the array.
* NOTE: This simple implementation only finds one mode.
* @param arr The array of integers.
* @param size The number of elements in the array.
* @return The mode value. Returns INT_MIN if array is empty.
*/
int find_mode(const int arr[], int size) {
if (size <= 0) {
return INT_MIN;
}
int mode = arr[0];
int max_count = 0;
for (int i = 0; i < size; i++) {
int current_element = arr[i];
int current_count = 0;
// Count occurrences of the current element
for (int j = 0; j < size; j++) {
if (arr[j] == current_element) {
current_count++;
}
}
// Update mode if the current element is more frequent
if (current_count > max_count) {
max_count = current_count;
mode = current_element;
}
}
// If max_count is 1, every element appeared only once (no clear mode)
// We return the most frequent one found (or the first element).
return mode;
}
/**
* @brief Calculates the median of the array elements.
* NOTE: This function relies on a sorted array. It creates a temporary copy
* to sort the data without modifying the original array.
* @param arr The array of integers.
* @param size The number of elements in the array.
* @return The median as a double. Returns DBL_MIN if array is empty.
*/
double calculate_median(const int arr[], int size) {
if (size <= 0) {
return DBL_MIN;
}
// 1. Create a copy of the array for sorting (to preserve original data)
int *temp_arr = (int*)malloc(size * sizeof(int));
if (temp_arr == NULL) {
// Handle memory allocation failure
return DBL_MIN;
}
// Copy data from const arr to temp_arr
for (int i = 0; i < size; i++) {
temp_arr[i] = arr[i];
}
// 2. Sort the temporary array
qsort(temp_arr, size, sizeof(int), compare_integers);
double median;
if (size % 2 == 1) {
// Odd number of elements: Median is the middle element
median = (double)temp_arr[size / 2];
} else {
// Even number of elements: Median is the average of the two middle
elements
int middle1 = temp_arr[size / 2 - 1];
int middle2 = temp_arr[size / 2];
median = (double)(middle1 + middle2) / 2.0;
}
// 3. Free the temporary array
free(temp_arr);
return median;
}
// --- MAIN EXECUTION ---
int main() {
int n;
int *numbers = NULL; // Pointer to the array
int min, max, range, mode;
double mean, median;
printf("--- Array Analysis Program ---\n");
// 1. Get the number of elements (N) from the user
do {
printf("Enter the number of elements (n > 0): ");
if (scanf("%d", &n) != 1 || n <= 0) {
printf("Invalid input. Please enter a positive integer.\n");
// Clear input buffer
while(getchar() != '\n');
n = 0; // Ensure loop continues
}
} while (n <= 0);
// 2. Dynamically allocate memory for the array
numbers = (int*)malloc(n * sizeof(int));
if (numbers == NULL) {
printf("Memory allocation failed. Exiting.\n");
return 1;
}
// 3. Input the N numbers from the user
printf("\n");
for (int i = 0; i < n; i++) {
printf("Enter element %d/%d: ", i + 1, n);
if (scanf("%d", &numbers[i]) != 1) {
printf("Invalid input. Exiting.\n");
free(numbers); // Free allocated memory before exit
while(getchar() != '\n');
return 1;
}
}
// 4. Calculate Statistics using Modular Functions
printf("\n--- Results ---\n");
// Mean
mean = calculate_mean(numbers, n);
if (mean != DBL_MIN) {
printf("Mean (Average): %.2f\n", mean);
}
// Median (New calculation)
median = calculate_median(numbers, n);
if (median != DBL_MIN) {
printf("Median: %.2f\n", median);
}
// Min and Max (for Range)
max = find_maximum(numbers, n);
min = find_minimum(numbers, n);
if (max != INT_MIN && min != INT_MAX) {
range = max - min;
printf("Maximum: %d\n", max);
printf("Minimum: %d\n", min);
printf("Range (Max - Min): %d\n", range);
}
// Mode
mode = find_mode(numbers, n);
if (mode != INT_MIN) {
printf("Mode (Most Frequent): %d\n", mode);
}
// 5. Free dynamically allocated memory
free(numbers);
return 0;
}
Output:
EXPERIMENT-35
Objective: Implement your own string length and string reversal
functions?
Theory: This program demonstrates fundamental string manipulation by
manually iterating through a character array to calculate its length and
create its reverse, without using built-in library functions.
Program:
#include <stdio.h>
#include <string.h> // Included for reference, but we implement our own
functions
#include <stdlib.h> // For EXIT_SUCCESS/FAILURE
// Define a maximum buffer size for the string input
#define MAX_STRING_LENGTH 100
// --- MODULAR FUNCTIONS ---
/**
* @brief Calculates the length of a null-terminated string (equivalent to
strlen).
* It iterates through the string character by character until it finds the
* null terminator ('\0').
* @param s The input string (a constant character pointer).
* @return The length of the string (number of characters excluding '\0').
*/
size_t custom_string_length(const char *s) {
// We use size_t for length, which is the standard unsigned integer type
// for sizes and counts in C.
size_t length = 0;
while (*s != '\0') {
length++;
s++; // Move the pointer to the next character
}
return length;
}
/**
* @brief Reverses a null-terminated string in place (equivalent to strrev).
* It uses two pointers, 'start' and 'end', to swap characters from the ends
* inward until they meet in the middle.
* @param s The input string (a non-const character pointer) to be reversed.
*/
void custom_string_reverse(char *s) {
if (s == NULL) {
return; // Handle null pointer case
}
// 1. Find the length of the string using our custom function
size_t length = custom_string_length(s);
// 2. Set up pointers for the start and end of the string
char *start = s;
char *end = s + length - 1; // Last character before the null terminator
// 3. Swap characters from the outside in
while (end > start) {
// Swap the characters pointed to by start and end
char temp = *start;
*start = *end;
*end = temp;
// Move pointers towards the middle
start++;
end--;
}
}
// --- MAIN EXECUTION ---
int main() {
char input_string[MAX_STRING_LENGTH];
size_t length;
printf("--- Custom String Length and Reversal Program ---\n");
printf("Enter a string (max %d characters):\n", MAX_STRING_LENGTH -
1);
// Safely read input string, leaving space for the null terminator
// scanf("%s", ...) is unsafe as it doesn't limit the characters read.
// fgets is safer, but we need to handle the newline character it includes.
if (fgets(input_string, MAX_STRING_LENGTH, stdin) == NULL) {
printf("Error reading input.\n");
return EXIT_FAILURE;
}
// Remove the newline character if it exists (added by fgets)
length = custom_string_length(input_string);
if (length > 0 && input_string[length - 1] == '\n') {
input_string[length - 1] = '\0';
}
// Recalculate length after potentially removing newline
length = custom_string_length(input_string);
printf("\n--- Results ---\n");
// 1. Calculate and display string length
printf("Original String: \"%s\"\n", input_string);
printf("Custom String Length: %zu\n", length);
// 2. Reverse the string in place
custom_string_reverse(input_string);
// 3. Display the reversed string
printf("Reversed String: \"%s\"\n", input_string);
// The length remains the same after reversal
printf("Length after Reversal: %zu\n",
custom_string_length(input_string));
return EXIT_SUCCESS;
}
Output:
EXPERIMENT-36
Objective: Design program to perform matrix operations addition,
subtraction and transpose?
Theory: This program implements fundamental linear algebra operations
(addition, subtraction and transpose) on two-dimensional arrays,
emphasizing the element-wise nature of matrix arithmetic and the row-
column swap for transposition.
Program:
#include <stdio.h>
#include <stdlib.h>
// Define a maximum size for the matrices (e.g., 10x10)
#define MAX_SIZE 10
// --- MODULAR FUNCTIONS ---
/**
* @brief Reads a matrix of size R x C from the user.
* @param matrix The 2D array (MAX_SIZE x MAX_SIZE) to store the
elements.
* @param R The number of rows.
* @param C The number of columns.
*/
void read_matrix(int matrix[MAX_SIZE][MAX_SIZE], int R, int C, const char
*name) {
printf("Enter elements for Matrix %s (%d x %d):\n", name, R, C);
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
printf("[%d][%d]: ", i + 1, j + 1);
// Input validation is omitted for brevity but recommended in
production code
if (scanf("%d", &matrix[i][j]) != 1) {
printf("Invalid input. Using 0 instead.\n");
matrix[i][j] = 0;
}
}
}
}
/**
* @brief Prints a matrix of size R x C.
* @param matrix The 2D array (MAX_SIZE x MAX_SIZE) to print.
* @param R The number of rows.
* @param C The number of columns.
*/
void print_matrix(const int matrix[MAX_SIZE][MAX_SIZE], int R, int C, const
char *name) {
printf("\nMatrix %s (%d x %d):\n", name, R, C);
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
printf("%5d ", matrix[i][j]);
}
printf("\n");
}
}
/**
* @brief Performs matrix addition (Result = A + B).
* This operation is only possible if A and B have the same dimensions (R x C).
* @param A The first matrix.
* @param B The second matrix.
* @param Result The matrix to store the sum.
* @param R The number of rows.
* @param C The number of columns.
*/
void matrix_add(const int A[MAX_SIZE][MAX_SIZE], const int
B[MAX_SIZE][MAX_SIZE],
int Result[MAX_SIZE][MAX_SIZE], int R, int C) {
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
Result[i][j] = A[i][j] + B[i][j];
}
}
}
/**
* @brief Performs matrix subtraction (Result = A - B).
* This operation is only possible if A and B have the same dimensions (R x C).
* @param A The first matrix.
* @param B The second matrix.
* @param Result The matrix to store the difference.
* @param R The number of rows.
* @param C The number of columns.
*/
void matrix_subtract(const int A[MAX_SIZE][MAX_SIZE], const int
B[MAX_SIZE][MAX_SIZE],
int Result[MAX_SIZE][MAX_SIZE], int R, int C) {
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
Result[i][j] = A[i][j] - B[i][j];
}
}
}
/**
* @brief Performs matrix transpose.
* The transpose of an R x C matrix is a C x R matrix.
* @param Original The original matrix (R x C).
* @param Transposed The matrix to store the transpose (C x R).
* @param R The number of rows in Original.
* @param C The number of columns in Original.
*/
void matrix_transpose(const int Original[MAX_SIZE][MAX_SIZE],
int Transposed[MAX_SIZE][MAX_SIZE], int R, int C) {
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
// Swap indices: Transposed[j][i] gets Original[i][j]
Transposed[j][i] = Original[i][j];
}
}
}
// --- MAIN EXECUTION ---
int main() {
int R1, C1; // Dimensions for Matrix A
int R2, C2; // Dimensions for Matrix B
int A[MAX_SIZE][MAX_SIZE];
int B[MAX_SIZE][MAX_SIZE];
int Result[MAX_SIZE][MAX_SIZE];
int Transposed[MAX_SIZE][MAX_SIZE];
char clear_buffer;
printf("--- Matrix Operations (Addition, Subtraction, Transpose) ---\n");
// 1. Get dimensions for Matrix A
printf("Enter number of rows for Matrix A (max %d): ", MAX_SIZE);
scanf("%d", &R1);
printf("Enter number of columns for Matrix A (max %d): ", MAX_SIZE);
scanf("%d", &C1);
// Basic dimension validation
if (R1 <= 0 || C1 <= 0 || R1 > MAX_SIZE || C1 > MAX_SIZE) {
printf("Invalid dimensions for Matrix A. Exiting.\n");
return 1;
}
// Clear input buffer after reading dimensions
while ((clear_buffer = getchar()) != '\n' && clear_buffer != EOF);
// 2. Read Matrix A
read_matrix(A, R1, C1, "A");
// 3. Get dimensions for Matrix B
printf("\n--- For Addition and Subtraction ---\n");
printf("Enter number of rows for Matrix B (must be %d): ", R1);
scanf("%d", &R2);
printf("Enter number of columns for Matrix B (must be %d): ", C1);
scanf("%d", &C2);
// Clear input buffer
while ((clear_buffer = getchar()) != '\n' && clear_buffer != EOF);
// 4. Read Matrix B only if dimensions match A for add/subtract
if (R1 == R2 && C1 == C2) {
read_matrix(B, R2, C2, "B");
print_matrix(A, R1, C1, "A");
print_matrix(B, R2, C2, "B");
// 5. Perform Addition
printf("\n--- Matrix Addition (A + B) ---\n");
matrix_add(A, B, Result, R1, C1);
print_matrix(Result, R1, C1, "A + B");
// 6. Perform Subtraction
printf("\n--- Matrix Subtraction (A - B) ---\n");
matrix_subtract(A, B, Result, R1, C1);
print_matrix(Result, R1, C1, "A - B");
} else {
printf("\nERROR: Matrices A and B have incompatible dimensions for
addition/subtraction.\n");
printf("Addition and Subtraction operations skipped.\n");
}
// 7. Perform Transpose on Matrix A
printf("\n--- Matrix Transpose (A^T) ---\n");
matrix_transpose(A, Transposed, R1, C1);
// The transposed matrix has C1 rows and R1 columns
print_matrix(Transposed, C1, R1, "A Transposed");
return 0;
}
Output:
EXPERIMENT-37
Objective: Write a recursive program to count the number of digits of a
positive integer number?
Theory: The program recursively counts the digits of a number by adding
one for each step and reducing the number by integer division by ten until
the number becomes zero, which serves as the base case.
Program:
#include <stdio.h>
#include <stdlib.h>
// --- MODULAR/RECURSIVE FUNCTION ---
/**
* @brief Recursively counts the number of digits in a positive integer.
* Base Case: If the number (n) is 0, it has 0 digits (or 1 if the initial input was
0,
* but for positive integers, we assume n > 0). The recursion stops when n is
0.
* Recursive Step: Divide n by 10 (integer division) and add 1 to the count,
* continuing the recursion with the new, smaller number.
* @param n The positive integer number.
* @return The number of digits in n.
*/
int count_digits_recursive(long long n) {
// Handle the specific case where the user inputs 0
if (n == 0) {
return 1;
}
// Ensure the number is treated as positive for counting
if (n < 0) {
n = -n;
}
// Base Case: If the number is reduced to 0, stop the recursion.
// However, since we are counting *down*, we start the count when n > 0.
if (n == 0) {
return 0;
}
// Recursive Step:
// 1 (current digit) + count of digits in the rest of the number (n/10)
return 1 + count_digits_recursive(n / 10);
}
// --- MAIN EXECUTION ---
int main() {
long long number;
int digit_count;
printf("--- Recursive Digit Counter Program ---\n");
printf("Enter a positive integer (or 0): ");
// Use long long to handle larger numbers
if (scanf("%lld", &number) != 1) {
printf("Invalid input. Exiting.\n");
return 1;
}
// Input validation for a positive integer
if (number < 0) {
printf("Input is negative. Counting digits of the absolute value.\n");
}
// Call the recursive function
digit_count = count_digits_recursive(number);
// Display the result
printf("\nNumber entered: %lld\n", number);
printf("Number of digits (recursive): %d\n", digit_count);
return 0;
}
Output:
EXPERIMENT-38
Objective: Recursive solutions for the following problems:
a. Factorial of a number
b. Display digits of a number from left to right and right to left
c. Compute xy using only multiplication?
d. To print a sequence of numbers entered using sentinel controlled
repetition in reverse order?
Theory: These problems collectively explore recursion by reducing each
task to a simpler, identical subproblem, relying on a defined base case for
termination across arithmetic (factorial, power) and sequence/data
manipulation (digits, reverse printing) functions.
Program:
#include <stdio.h>
#include <stdlib.h>
// --- MODULAR RECURSIVE FUNCTIONS ---
// Problem a: Factorial of a number
/**
* @brief Recursively calculates the factorial of a non-negative integer n (n!).
* Base Case: Factorial of 0 is 1.
* Recursive Step: n! = n * (n-1)!
* @param n The non-negative integer.
* @return The factorial of n as a long long.
*/
long long recursive_factorial(int n) {
if (n < 0) {
return -1; // Error indicator for negative input
}
// Base Case: 0! = 1
if (n == 0) {
return 1;
}
// Recursive Step
return (long long)n * recursive_factorial(n - 1);
}
// Problem c: Compute x^y using only multiplication (recursive power
function)
/**
* @brief Recursively computes the power x^y using only multiplication.
* Base Case: x^0 = 1.
* Recursive Step: x^y = x * x^(y-1)
* @param x The base number.
* @param y The non-negative exponent.
* @return The result of x raised to the power y.
*/
long long recursive_power(int x, int y) {
if (y < 0) {
// Simple case for non-negative y only, as requested by 'only
multiplication' constraint
printf("Error: Power function is designed for non-negative
exponents.\n");
return -1;
}
// Base Case: x^0 = 1
if (y == 0) {
return 1;
}
// Recursive Step
return (long long)x * recursive_power(x, y - 1);
}
// Problem b: Display digits of a number from left-to-right
/**
* @brief Recursively displays the digits of a number from left to right.
* Base Case: If n < 10, print the digit and return.
* Recursive Step: Call the function on n/10 first, then print n % 10.
* @param n The positive integer number.
*/
void display_digits_ltr(long long n) {
if (n < 0) {
// Handle negative sign, then recurse with the absolute value
printf("-");
display_digits_ltr(-n);
return;
}
// Base Case
if (n < 10) {
printf("%lld ", n);
return;
}
// Recursive Call (processes the left digits first)
display_digits_ltr(n / 10);
// Print the last digit after the recursive call returns
printf("%lld ", n % 10);
}
// Problem b: Display digits of a number from right-to-left
/**
* @brief Recursively displays the digits of a number from right to left
(reverse order).
* Base Case: If n == 0, stop.
* Recursive Step: Print n % 10 first, then call the function on n/10.
* @param n The positive integer number.
*/
void display_digits_rtl(long long n) {
if (n < 0) {
// Handle negative sign, then recurse with the absolute value
display_digits_rtl(-n);
printf("-");
return;
}
// Base Case
if (n == 0) {
return;
}
// Print the last digit first
printf("%lld ", n % 10);
// Recursive Call (processes the remaining digits)
display_digits_rtl(n / 10);
}
// Problem d: Print a sequence of numbers entered using sentinel controlled
repetition in reverse order
/**
* @brief Reads integers until a sentinel (e.g., 0) is entered, then prints them
* in reverse order using recursion.
* The recursion manages the stack to store the numbers in the correct
sequence.
* The printing happens on the way back up the stack (after the recursive
call).
* @param sentinel The value that terminates input (e.g., 0).
*/
void print_reverse_sentinel(int sentinel) {
int number;
// Read the current number
if (scanf("%d", &number) != 1) {
// Handle input error
return;
}
// Check for the sentinel value
if (number != sentinel) {
// Recursive Step: Call itself to read the next number
print_reverse_sentinel(sentinel);
// Action on the way back up the stack (print in reverse order)
printf("%d ", number);
}
// Base Case: If number == sentinel, the function returns without printing
// the sentinel, effectively ending the recursion path.
}
// --- MAIN EXECUTION ---
int main() {
long long num_for_digits = 12345;
int base_x = 2;
int exponent_y = 10;
int factorial_n = 5;
printf("--- Recursive Solutions Demonstration ---\n\n");
// a. Factorial of a number
long long fact_result = recursive_factorial(factorial_n);
printf("a. Factorial (%d!):\n", factorial_n);
if (fact_result != -1) {
printf("Result: %lld\n", fact_result);
} else {
printf("Invalid input for factorial.\n");
}
printf("-----------------------------------------\n");
// c. Compute x^y using only multiplication
long long power_result = recursive_power(base_x, exponent_y);
printf("c. Power (%d^%d):\n", base_x, exponent_y);
if (power_result != -1) {
printf("Result: %lld\n", power_result);
} else {
printf("Invalid input for power.\n");
}
printf("-----------------------------------------\n");
// b. Display digits of a number
printf("b. Display Digits of %lld:\n", num_for_digits);
printf(" Left-to-Right: ");
display_digits_ltr(num_for_digits);
printf("\n");
printf(" Right-to-Left: ");
display_digits_rtl(num_for_digits);
printf("\n");
printf("-----------------------------------------\n");
// d. Print sequence of numbers in reverse order (Sentinel Controlled)
printf("d. Print sequence of numbers in reverse order (Sentinel = 0):\n");
printf(" Enter numbers (end with 0):\n");
// Call the recursive function to handle input and reverse printing
print_reverse_sentinel(0);
printf("\n\n--- Input sequence printed in reverse. ---\n");
// Note on problem d: The print_reverse_sentinel function relies on
// standard input (stdin) for user interaction.
return 0;
}
Output: