Basic Function Programming Questions

Here are 10 C programming exercises that involve writing and using functions:

  1. Calculate Area of a Circle: Write a program that calculates the area of a circle. Use a function to take the radius as input and return the area.

  2. Factorial Calculation: Create a program to calculate the factorial of a given number. Write a function to perform the factorial calculation.

  3. Palindrome Check: Implement a function to check if a given string is a palindrome (reads the same backward as forward). Ignore spaces and consider case.

  4. Sum of Array Elements: Write a program that calculates the sum of elements in an array. Use a function to perform the summation.

  5. Reverse a String: Implement a function to reverse a string. Modify the original string in place.

  6. Prime Number Checker: Create a program to check if a given number is prime. Use a function to perform the prime checking.

  7. Calculate Power: Write a program that calculates the power of a number. Create a function that takes the base and exponent as parameters and returns the result.

  8. Fibonacci Series: Generate the first N terms of the Fibonacci series. Implement a function to calculate each term.

  9. GCD (Greatest Common Divisor): Write a program to find the GCD of two numbers. Create a function to calculate the GCD using the Euclidean algorithm.

  10. Matrix Multiplication: Implement a program that multiplies two matrices. Define a function to perform the matrix multiplication.

These exercises cover a range of function-related concepts and will help you practice and strengthen your skills in C programming. I have solved all of the above with explanatory comments. You should first make a sincere attempt at solving these problems before looking at the solutions.

1. Calculate Area of a Circle

#include <stdio.h>

// Function to calculate the area of a circle
float calculateArea(float radius) {
    // Define the value of pi
    float pi = 3.14159;

    // Calculate the area using the formula: area = pi * radius * radius
    float area = pi * radius * radius;

    // Return the calculated area
    return area;
}

// Main function where the program execution begins
int main() {
    // Declare variables to store radius and area
    float radius, area;

    // Prompt the user to enter the radius
    printf("Enter the radius of the circle: ");

    // Read the user input and store it in the 'radius' variable
    scanf("%f", &radius);

    // Check if the entered radius is non-negative
    if (radius >= 0) {
        // Call the calculateArea function to compute the area
        area = calculateArea(radius);

        // Display the result with two decimal places
        printf("The area of the circle with radius %.2f is: %.2f\n", radius, area);
    } else {
        // Display an error message if the radius is negative
        printf("Error: Radius cannot be negative.\n");
    }

    // Indicate successful program execution to the operating system
    return 0;
}

2. Factorial Calculation

#include <stdio.h>

// Function to calculate factorial
int factorial(int n) {
    // Base case: factorial of 0 or 1 is 1
    if (n <= 1) 
        return 1;

    // Recursive case: n! = n * (n-1)!
    return n * factorial(n - 1);
}

// Main function where the program execution begins
int main() {
    // Declare variable to store user input
    int num;

    // Prompt the user to enter a positive integer
    printf("Enter a positive integer: ");

    // Read the user input and store it in the 'num' variable
    scanf("%d", &num);

    // Check if the entered number is non-negative
    if (num >= 0) {
        // Call the factorial function to compute the factorial
        printf("Factorial of %d is %d\n", num, factorial(num));
    } else {
        // Display an error message if the entered number is negative
        printf("Error: Enter a positive integer.\n");
    }

    // Indicate successful program execution to the operating system
    return 0;
}

3. Palindrome Check

#include <stdio.h>
#include <string.h>

// Function to check if a string is palindrome
int isPalindrome(char str[]) {
    // Get the length of the input string
    int len = strlen(str);

    // Iterate over the first half of the string
    for (int i = 0; i < len / 2; i++) {
        // Compare characters from the beginning and end of the string
        if (str[i] != str[len - i - 1]) {
            // If characters do not match, return 0 (not a palindrome)
            return 0;
        }
    }

    // If the loop completes without returning, the string is a palindrome
    return 1;
}

// Main function where the program execution begins
int main() {
    // Declare an array to store the user input string
    char str[100];

    // Prompt the user to enter a string
    printf("Enter a string: ");

    // Read the user input and store it in the 'str' array
    scanf("%s", str);

    // Check if the entered string is a palindrome
    if (isPalindrome(str)) {
        // Display the result if the string is a palindrome
        printf("%s is a palindrome.\n", str);
    } else {
        // Display the result if the string is not a palindrome
        printf("%s is not a palindrome.\n", str);
    }

    // Indicate successful program execution to the operating system
    return 0;
}

4. Sum of Array Elements

#include <stdio.h>

// Function to calculate sum of elements in an array
int arraySum(int arr[], int n) {
    // Initialize a variable to store the sum of array elements
    int sum = 0;

    // Iterate through each element of the array
    for (int i = 0; i < n; i++) {
        // Add the current element to the sum
        sum += arr[i];
    }

    // Return the calculated sum
    return sum;
}

// Main function where the program execution begins
int main() {
    // Declare variables to store the number of elements and the array
    int n, arr[100];

    // Prompt the user to enter the number of elements
    printf("Enter number of elements: ");

    // Read the user input and store it in the 'n' variable
    scanf("%d", &n);

    // Prompt the user to enter the elements of the array
    printf("Enter %d elements:\n", n);

    // Loop to read the elements and store them in the array
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    // Call the arraySum function to calculate the sum of array elements
    printf("Sum of array elements is %d\n", arraySum(arr, n));

    // Indicate successful program execution to the operating system
    return 0;
}

5. Reverse a String

#include <stdio.h>
#include <string.h>

// Function to reverse a string
void reverseString(char str[]) {
    int len = strlen(str);
    for (int i = 0, j = len - 1; i < j; i++, j--) {
        char temp = str[i];
        str[i] = str[j];
        str[j] = temp;
    }
}

int main() {
    char str[100];
    printf("Enter a string: ");
    scanf("%s", str);
    reverseString(str);
    printf("Reversed string: %s\n", str);
    return 0;
}

6. Prime Number Checker

#include <stdio.h>
#include <string.h>

// Function to reverse a string
void reverseString(char str[]) {
    // Get the length of the input string
    int len = strlen(str);

    // Iterate over the first half of the string
    // Swap characters from the beginning and end of the string
    for (int i = 0, j = len - 1; i < j; i++, j--) {
        // Use a temporary variable to swap characters
        char temp = str[i];
        str[i] = str[j];
        str[j] = temp;
    }
}

// Main function where the program execution begins
int main() {
    // Declare an array to store the user input string
    char str[100];

    // Prompt the user to enter a string
    printf("Enter a string: ");

    // Read the user input and store it in the 'str' array
    scanf("%s", str);

    // Call the reverseString function to reverse the entered string
    reverseString(str);

    // Display the reversed string
    printf("Reversed string: %s\n", str);

    // Indicate successful program execution to the operating system
    return 0;
}

7. Calculate Power

#include <stdio.h>

// Function to calculate power of a number
double power(double base, int exponent) {
    // Initialize a variable to store the result
    double result = 1.0;

    // Iterate 'exponent' times and multiply 'base' with itself
    for (int i = 0; i < exponent; i++) {
        result *= base;
    }

    // Return the calculated result
    return result;
}

// Main function where the program execution begins
int main() {
    // Declare variables to store the base, result, and exponent
    double base, result;
    int exponent;

    // Prompt the user to enter the base and exponent
    printf("Enter base and exponent: ");

    // Read the user input for base and exponent and store in respective variables
    scanf("%lf %d", &base, &exponent);

    // Call the power function to calculate the result
    result = power(base, exponent);

    // Display the result with two decimal places
    printf("%.2lf raised to power %d is %.2lf\n", base, exponent, result);

    // Indicate successful program execution to the operating system
    return 0;
}

8. Fibonacci Series

#include <stdio.h>

// Function to print Fibonacci series
void fibonacci(int n) {
    // Initialize variables to store the first two terms of the series
    int a = 0, b = 1, c;

    // Display a message indicating the number of terms to be printed
    printf("Fibonacci series up to %d terms:\n", n);

    // Loop to generate and print the Fibonacci series
    for (int i = 0; i < n; i++) {
        // Print the current term of the series
        printf("%d ", a);

        // Calculate the next term in the series (sum of the previous two terms)
        c = a + b;

        // Update variables for the next iteration
        a = b;
        b = c;
    }

    // Print a newline character to separate the series from other output
    printf("\n");
}

// Main function where the program execution begins
int main() {
    // Declare a variable to store the number of terms
    int n;

    // Prompt the user to enter the number of terms
    printf("Enter number of terms: ");

    // Read the user input for the number of terms and store it in the variable 'n'
    scanf("%d", &n);

    // Call the fibonacci function to generate and print the series
    fibonacci(n);

    // Indicate successful program execution to the operating system
    return 0;
}

9. GCD (Greatest Common Divisor)

#include <stdio.h>

// Function to calculate GCD using Euclidean algorithm
int gcd(int a, int b) {
    // Keep looping until 'b' becomes 0
    while (b != 0) {
        // Store the value of 'b' in a temporary variable
        int temp = b;

        // Update 'b' with the remainder of 'a' divided by 'b'
        b = a % b;

        // Update 'a' with the previous value of 'b'
        a = temp;
    }

    // When 'b' becomes 0, 'a' contains the GCD
    return a;
}

// Main function where the program execution begins
int main() {
    // Declare variables to store two positive integers
    int num1, num2;

    // Prompt the user to enter two positive integers
    printf("Enter two positive integers: ");

    // Read the user input for the two integers and store them in the variables 'num1' and 'num2'
    scanf("%d %d", &num1, &num2);

    // Call the gcd function to calculate the GCD and display the result
    printf("GCD of %d and %d is %d\n", num1, num2, gcd(num1, num2));

    // Indicate successful program execution to the operating system
    return 0;
}

10. Matrix Multiplication.

#include <stdio.h>

// Function to perform matrix multiplication
void multiplyMatrices(int firstMatrix[10][10], int secondMatrix[10][10], int result[10][10], int rowFirst, int colFirst, int rowSecond, int colSecond) {
    // Initialize the result matrix with zeros
    for (int i = 0; i < rowFirst; ++i) {
        for (int j = 0; j < colSecond; ++j) {
            result[i][j] = 0;
        }
    }

    // Perform matrix multiplication
    for (int i = 0; i < rowFirst; ++i) {
        for (int j = 0; j < colSecond; ++j) {
            for (int k = 0; k < colFirst; ++k) {
                // Multiply corresponding elements and accumulate the result
                result[i][j] += firstMatrix[i][k] * secondMatrix[k][j];
            }
        }
    }
}

// Function to display a matrix
void displayMatrix(int matrix[10][10], int row, int col) {
    printf("Matrix:\n");
    for (int i = 0; i < row; ++i) {
        for (int j = 0; j < col; ++j) {
            // Print each element of the matrix
            printf("%d\t", matrix[i][j]);
        }
        // Move to the next row in the output
        printf("\n");
    }
}

int main() {
    int rowFirst, colFirst, rowSecond, colSecond;

    // Input the dimensions of the first matrix
    printf("Enter dimensions of the first matrix (rows and columns): ");
    scanf("%d %d", &rowFirst, &colFirst);

    // Input the dimensions of the second matrix
    printf("Enter dimensions of the second matrix (rows and columns): ");
    scanf("%d %d", &rowSecond, &colSecond);

    // Check if matrix multiplication is possible
    if (colFirst != rowSecond) {
        printf("Error: Matrix multiplication is not possible.\n");
        return 0;
    }

    int firstMatrix[10][10], secondMatrix[10][10], result[10][10];

    // Input elements of the first matrix
    printf("Enter elements of the first matrix:\n");
    for (int i = 0; i < rowFirst; ++i) {
        for (int j = 0; j < colFirst; ++j) {
            // Read each element from the user
            scanf("%d", &firstMatrix[i][j]);
        }
    }

    // Input elements of the second matrix
    printf("Enter elements of the second matrix:\n");
    for (int i = 0; i < rowSecond; ++i) {
        for (int j = 0; j < colSecond; ++j) {
            // Read each element from the user
            scanf("%d", &secondMatrix[i][j]);
        }
    }

    // Perform matrix multiplication
    multiplyMatrices(firstMatrix, secondMatrix, result, rowFirst, colFirst, rowSecond, colSecond);

    // Display the input matrices
    printf("\n");
    displayMatrix(firstMatrix, rowFirst, colFirst);
    printf("\n");
    displayMatrix(secondMatrix, rowSecond, colSecond);

    // Display the result matrix
    printf("\nResult of matrix multiplication:\n");
    displayMatrix(result, rowFirst, colSecond);

    return 0;
}