Apply for Zend Framework Certification Training

c

< Pattern using loop in c Part - 2 Standard C Libraries with Examples >




Functions in C Programming
A function in C is a block of code that performs a specific task. We use functions to divide a large program into smaller, reusable parts.
For example, instead of writing addition logic repeatedly, we can create one function called add() and call it whenever required.
1. Advantages of Functions
- Code reusability: Write once, use many times.
- Modularity: Divide a large program into smaller parts.
- Easy debugging: Find and fix errors more easily.
- Readability: Make programs easier to understand.
- Less duplication: Avoid writing the same code repeatedly.
2. Types of Functions in C
There are two main categories.
Functions in C
1. Library Functions
Predefined functions provided by C libraries.
Examples: printf(), scanf(), strlen(), sqrt()
2. User-Defined Functions
Functions created by the programmer.
Examples: add(), factorial(), display()
3. Three Important Parts of a Function
1. Function declaration (prototype): Tells the compiler the function's name, return type, and parameters.
2. Function definition: Contains the actual code.
3. Function call: Executes the function.
Example: Addition of Two Numbers
#include <stdio.h>
// 1. Function declaration
int add(int, int);
int main() {
    int result;
    // 2. Function call
    result = add(10, 20);
    printf("Sum = %d", result);
    return 0;
}
// 3. Function definition
int add(int a, int b) {
    return a + b;
}
Output:
Sum = 30
Explanation:
- int add(int, int); declares the function.
- add(10, 20) calls the function.
- int add(int a, int b) defines the function.
- return a + b; sends the result back to main().
4. Four Categories of User-Defined Functions
These categories depend on whether the function accepts arguments and returns a value.
1 No arguments, no return value
void greet(void) {
    printf("Hello Students!");
}
Call: greet();
2 Arguments, no return value
void add(int a, int b) {
    printf("%d", a + b);
}
Call: add(10, 20);
3 No arguments, returns a value
int getNumber(void) {
    return 100;
}
Call: int n = getNumber();
4 Arguments and returns a value
int multiply(int a, int b) {
    return a * b;
}
Call: int result = multiply(5, 4);
5. Actual Arguments vs Formal Parameters
int add(int a, int b) {  // a and b are formal parameters
    return a + b;
}
int main() {
    int result = add(5, 7); // 5 and 7 are actual arguments
    return 0;
}
- Actual arguments: Values or expressions passed during a function call.
- Formal parameters: Variables that receive those values inside the function.
7. Some practical Examples
#include <stdio.h>
void registration(char email[], char password[], int age) {
    printf("This is registration function\n");
    printf("Email: %s\n", email);
    printf("Password: %s\n", password);
    printf("Age: %d\n", age);
}
void Login() {
    printf("This is Login function\n");
}
void forgotPassword() {
    printf("This is forgotPassword function\n");
}
int main() {
    int n = 1;
    switch (n) {
        case 1:
            registration("xyz@gmail.com", "dsds", 23);
            break;
        case 2:
            Login();
            break;
        case 3:
            forgotPassword();
            break;
        default:
            printf("Please enter correct choice\n");
    }

    return 0;
}
6. Call by Value and Call by Reference
In C, arguments are passed by value. A function receives copies of the supplied values.
#include <stdio.h>
void change(int x) {
    x = 100;
}
int main() {
    int a = 10;
    change(a);
    printf("%d", a);
    return 0;
}
Output:
10
The original a remains 10 because change() modifies only its local copy.
To modify the original variable, pass its address using a pointer:
#include <stdio.h>
void change(int *x) {
    *x = 100;
}
int main() {
    int a = 10;
    change(&a);
    printf("%d", a);
    return 0;
}
Output:
100
This is commonly called call by reference using pointers, although the C language formally passes the pointer itself by value.
7. Recursion in C
Recursion occurs when a function calls itself. It must have a base condition to stop further calls.
Example: Factorial of a number.
#include <stdio.h>
int factorial(int n) {
    if (n <= 1) {
        return 1;
    }
    return n * factorial(n - 1);
}
int main() {
    printf("%d", factorial(5));
    return 0;
}
Output:
120
Calculation:
5! = 5*4*3*2*1 = 120
1. Factorial of a Number
Question: Write a C program to calculate the factorial of a number using recursion.
#include <stdio.h>
int factorial(int n) {
    if (n <= 1) {
        return 1;
    }
    return n * factorial(n - 1);
}
int main() {
    int n = 5;
    printf("Factorial = %d", factorial(n));
    return 0;
}
Output:
Factorial = 120
How it works:
5! = 5 times 4 times 3 times 2 times 1 = 120
Recursion flow
factorial(5) = 5 × factorial(4)
factorial(4) = 4 × factorial(3)
factorial(3) = 3 × factorial(2)
factorial(2) = 2 × factorial(1)
factorial(1) = 1  [Base condition]
2. Sum of Natural Numbers
Question: Calculate the sum of numbers from 1 to n using recursion.
#include <stdio.h>
int sum(int n) {
    if (n == 0) {
        return 0;
    }
    return n + sum(n - 1);
}
int main() {
    printf("Sum = %d", sum(5));
    return 0;
}
Output:
Sum = 15
Explanation:
sum(5) = 5 + 4 + 3 + 2 + 1 = 15.
3. Fibonacci Series Using Recursion
Question: Write a C program to find the Fibonacci number at position n, using the convention that positions start at 0.
#include <stdio.h>
int fibonacci(int n) {
    if (n == 0) {
        return 0;
    }
    if (n == 1) {
        return 1;
    }
    return fibonacci(n - 1) + fibonacci(n - 2);
}
int main() {
    int i;
    for (i = 0; i < 7; i++) {
        printf("%d ", fibonacci(i));
    }
    return 0;
}
Output:
0 1 1 2 3 5 8
Explanation: Each Fibonacci number is the sum of the previous two numbers. This simple recursive implementation is suitable for learning but becomes slow for large values of n.
4. Print Numbers from 1 to N
Question: Print numbers from 1 to 5 without using a loop.
#include <stdio.h>
void printNumbers(int n) {
    if (n == 0) {
        return;
    }
    printNumbers(n - 1);
    printf("%d ", n);
}
int main() {
    printNumbers(5);
    return 0;
}
Output:
1 2 3 4 5
Important: The recursive call happens before printf(), so the numbers are printed in ascending order.
5. Print Numbers from N to 1
Question: Print numbers from 5 to 1 using recursion.
#include <stdio.h>
void printReverse(int n) {
    if (n == 0) {
        return;
    }
    printf("%d ", n);
    printReverse(n - 1);
}
int main() {
    printReverse(5);
    return 0;
}
Output:
5 4 3 2 1
Here, printf() runs before the recursive call, so the numbers are printed in descending order.
6. Calculate Power of a Number
Question: Calculate (2^5) using recursion.
#include <stdio.h>
int power(int base, int exp) {
    if (exp == 0) {
        return 1;
    }
    return base * power(base, exp - 1);
}
int main() {
    printf("Power = %d", power(2, 5));
    return 0;
}
Output:
Power = 32
Explanation: 25=22222=32.
This example assumes a non-negative exponent and small enough values to avoid integer overflow.
7. Count Digits in a Number
Question: Count the digits of 12345 using recursion.
#include <stdio.h>
int countDigits(int n) {
    if (n >= 0 && n < 10) {
        return 1;
    }
    return 1 + countDigits(n / 10);
}
int main() {
    printf("Digits = %d", countDigits(12345));
    return 0;
}
Output:
Digits = 5
Explanation:
- 12345 / 10 gives 1234
- 1234 / 10 gives 123
- 123 / 10 gives 12
- 12 / 10 gives 1
- At 1, the base condition is reached.
This version assumes a non-negative integer.
8. Find the Sum of Digits
Question: Find the sum of digits of 1234 using recursion.
#include <stdio.h>
int digitSum(int n) {
    if (n == 0) {
        return 0;
    }
    return n % 10 + digitSum(n / 10);
}
int main() {
    printf("Sum of digits = %d", digitSum(1234));
    return 0;
}
Output:
Sum of digits = 10
Calculation: 1+2+3+4=10.
9. Reverse a Number Using Recursion
Question: Reverse 1234 using recursion.
#include <stdio.h>
int reverseHelper(int n, int rev) {
    if (n == 0) {
        return rev;
    }
    return reverseHelper(n / 10, rev * 10 + n % 10);
}
int main() {
    printf("Reverse = %d", reverseHelper(1234, 0));
    return 0;
}
Output:
Reverse = 4321
The helper function extracts the last digit using % 10 and appends it to the reversed number.
10. Find GCD Using Recursion
Question: Find the greatest common divisor (GCD) of 24 and 18.
#include <stdio.h>
int gcd(int a, int b) {
    if (b == 0) {
        return a;
    }
    return gcd(b, a % b);
}
int main() {
    printf("GCD = %d", gcd(24, 18));
    return 0;
}
Output:
GCD = 6

< Pattern using loop in c Part - 2 Standard C Libraries with Examples >



Ask a question



  • Question:
    {{questionlistdata.blog_question_description}}
    • Answer:
      {{answer.blog_answer_description  }}
    Replay to Question


Back to Top