Chapter - 7 Functions in C, Computer Science, Class 10 / class 10, ASSEB (SEBA), Prepared by Podmeswar through AI

 Warning Disclaimer Notice:

The below answers and discussions are directly prepared by copy-paste from www.google.com, Googole AI Overview,  https://gemini.google.com/app , https://chatgpt.com/,etc,

These are only for understanding to improve the concept only; not for answers. We have not checked these clearly. Some mistakes may be happened. We are not responsible for any wrong information and answers. Please check yourself, yourselves and discuss with your expert teachers for the final approval or accepted the answers.  


Functions in C 7

Example 7.1 A C program using a function.

Answer:

#include<stdio.h>

int sum (int a, int b);

 

int main()

{

int a = 4, b = 5, result;

result=sum(a,b);

 

printf(“\n result is: %d”, result);

 

return 0;

}

 

int sum(int a, int b)

{

int result=a+b;

return result;

}

Meaning:

It looks like you've provided a standard C program that demonstrates the complete lifecycle of a function. This code is a great example of modular programming, where the logic for addition is separated from the main execution.

Breakdown of your code:

1.       Prototype: int sum (int a, int b); — This alerts the compiler that a function named sum exists and expects two integers.

2.       Arguments vs. Parameters:

o    In main(), a and b are Actual Arguments (the real values being sent).

o    In sum(), a and b are Formal Parameters (local variables that receive the values).

3.       Scope: Notice that you have a variable named result in both main() and sum(). Because of local scope, these are two completely different containers in memory; the result inside sum only exists until the function returns.


A Small Correction for Clean Execution

Your code is logically perfect, but there is one tiny typographical detail to watch out for: the quotation marks in your printf statement.

In C programming, you must use straight quotes ("...") rather than "smart" or curly quotes (“...”), which often appear if you copy-paste from a word processor.

 

 

 

Here is the corrected version of your snippet:

C

#include <stdio.h>

 

int sum(int a, int b); // Prototype

 

int main() {

    int a = 4, b = 5, result;

   

    // The value returned by sum() is stored in the local 'result'

    result = sum(a, b);

   

    // Fixed the quotation marks here:

    printf("\n result is: %d", result);

   

    return 0;

}

 

int sum(int a, int b) {

    int result = a + b;

    return result; // Value 9 is sent back to main

}

Execution Flow

1.        main starts and initializes a=4 and b=5.

2.        main pauses and jumps to sum().

3.        sum creates its own a and b, calculates 9, and "hands" it back to main.

4.        main resumes, stores that 9 in its own result variable, and prints it.

Would you like to see how you can make this function even shorter using a single-line return statement?

Based on the code you provided, the program will calculate the sum of the two integers and display the result on the screen.

The Output

Plaintext

 result is: 9


Execution Trace

To understand how the computer arrived at 9, here is the step-by-step trace of the memory and execution:

1.        Initialization: The variables a and b in main() are assigned 4 and 5.

2.        The Call: When sum(a, b) is called, the values are passed into the function.

3.        The Calculation: Inside the sum function, a local variable result is created. It calculates $4 + 5$, resulting in 9.

4.        The Return: The value 9 is "thrown" back to the main() function.

5.        The Assignment: In main(), the result variable receives that 9.

6.        The Print: The printf statement outputs the final value.

Common "Gotcha" with this Output

If you were to change the values of a or b inside the sum function, the a and b in main would not change. This is because C uses Pass by Value, meaning the function only gets a copy of the numbers, not the original variables themselves.

Would you like me to show you how the output changes if we use user input via scanf instead of fixed numbers?


 

Example 7.1 A C program using a function.

Finding summation of two numbers:

Let us write a function to find the summation of two integers.

Answer:

#include<stdio.h>

int sum (int a, int b);

int main()

{

int a, b, result;

printf("\n Enter the first number: ");

scanf("%d", &a);

printf("\n Enter the second number: ");

scanf("%d", &b);

result = sum(a, b);

printf("\n Result is: %d", result);

return 0;

}

int sum(int a, int b)

{

int result;

result = a + b;

return result;

}

Meaning:

This C program calculates the sum of two user-inputted integers using a custom function

. It prompts for two numbers, adds them via the sum function, and prints the result. Based on input 5 and 10, the output will be: 

text

 Enter the first number: 5

 Enter the second number: 10

 Result is: 15

Step-by-step Execution: 

  1. Enter the first number: is printed.
  2. The program waits for user input (e.g., 5).
  3. Enter the second number: is printed.
  4. The program waits for user input (e.g., 10).
  5. sum(5, 10) returns

5+10=155 plus 10 equals 15

5+10=15

.

  1. Result is: 15 is printed. 

This C program calculates the sum of two user-inputted integers using a custom function. It defines sum(int a, int b), which adds two numbers and returns the result to the main() function. The program then prints the final sum. 

Code Breakdown:

·         #include<stdio.h>: Includes the standard I/O library for printf and scanf.

·         int sum(int a, int b);: Function prototype (declaration).

·         main(): Executes input, calls sum, and prints the output.

·         scanf("%d", &a);: Reads integer input from the user.

·         sum(a, b): Function call to calculate the sum.

·         return result;: Returns the calculated sum, a + b, to the caller. 

Execution Example:

text

Enter the first number: 5

Enter the second number: 10

Result is: 15

 


 

Example 7.2 A C program using a function with extra printf().

Answer:

#include<stdio.h>

int sum (int a, int b);

int main()

{

int a, b, result;

printf("\n Enter the first number: ");

scanf("%d", &a);

printf("\n Enter the second number: ");

scanf("%d", &b);

printf("\n Program control: just before making function call.");

result = sum(a, b);

printf("\n Program control: just after return from function call.");

printf("\n Result is: %d", result);

return 0;

}

int sum(int a, int b)

{

printf("\n Program control: inside function definition.");

int result;

result = a + b;

return result;

}

Meaning & Output

The provided C program prompts for two integers, displays execution control flow messages, calculates their sum using a function, and outputs the final result. Assuming user input is 5 and 3, the output shows the sequence of printf statements, the function call, and the final result. 

 

Example Output:

text

 Enter the first number: 5

 Enter the second number: 3

 Program control: just before making function call.

 Program control: inside function definition.

 Program control: just after return from function call.

 Result is: 8

 

Breakdown: This C program calculates the sum of two user-inputted integers using a custom function. It defines sum to add two integers and calls it from main, printing debug messages to show the program flow: from main, into the function, and back to main to display the result. 

Program Flow & Output Example:
If the user inputs 
5 and 10, the output will be:

text

 Enter the first number: 5

 Enter the second number: 10

 Program control: just before making function call.

 Program control: inside function definition.

 Program control: just after return from function call.

 Result is: 15

Key Components:

·         Function Prototype: int sum (int a, int b); declares the function before it is used.

·         Function Call: result = sum(a, b); passes user inputs to the function.

·         Function Definition: int sum(int a, int b) { ... } receives parameters, calculates $a + b$, and returns the result.

·         Control Flow: The printf statements before/after sum(a,b) and inside the function demonstrate the execution order. 

 


 

Example 7.3: A C program for finding the largest among three numbers using a function.

Answer:

#include<stdio.h>

int find_largest (int a, int b, int c);

int main()

{

int a, b, c, largest = 0;

printf("\n Enter the first number: ");

scanf("%d", &a);

printf("\n Enter the second number: ");

scanf("%d", &b);

printf("\n Enter the third number: ");

scanf("%d", &c);

largest = find_largest(a, b, c);

printf("\n Largest number is: %d", largest);

return 0;

}

int find_largest ( int a, int b, int c )

{

int largest = 0;

if ( a > b )

{

if ( a > c )

largest = a;

else

largest = c;

}

else

{

if ( b > c )

largest = b;

else

largest = c;

}

return largest;

}

 

Meaning and Output:

The provided C code prompts the user to enter three numbers. The output will vary depending on the numbers the user enters.

Here is an example of the program's execution and output, assuming the user enters 1045, and 20:

 Enter the first number: 10

 Enter the second number: 45

 Enter the third number: 20

 Largest number is: 45

If you run the program and enter different values, the final output will display the largest of those three numbers. 

 

The provided C code is a complete and working program designed to find the largest of three numbers entered by the user. 

Code Description

The program consists of two main functions:

1.    main(): This function handles user input using printf and scanf, calls the find_largest function to determine the maximum value, and then prints the final result.

2.    find_largest(int a, int b, int c): This function accepts three integer arguments and uses a series of nested if-else statements to compare the numbers and return the largest one. 

Analysis of the Logic

The logic within the find_largest function effectively determines the largest number by comparing the values in a structured way:

·         It first checks if a is greater than b.

o    If true, it compares a with c to find the largest between the two.

o    If false, it means b is greater than or equal to a, so it proceeds to compare b with c

Alternative Implementation

The logic can be simplified using the ternary operator, which is more concise for this type of problem: 

c

int find_largest_simplified ( int a, int b, int c )

{

    // Compares a and b, then compares the larger of the two with c

    int largest = (a > b) ? (a > c ? a : c) : (b > c ? b : c);

    return largest;

}

 

 

 

Example 7.4: A C program for finding the largest among a series of numbers.

Answer:

#include<stdio.h>

int find_largest (int);

int number[20];

int main()

{

int totalEle, largest = 0;

printf("\n Enter total number of elements in the series: ");

scanf("%d", &totalEle);

printf("\n Taking input to the array elements: ");

for(int i=0; i<totalEle; i++)

{

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

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

}

largest = find_largest(totalEle);

printf("\n Largest number is: %d", largest);

return 0;

}

int find_largest( int totalEle)

{

int largest = number[0];

for(int i=1; i<totalEle; i++)

{

if ( number[i] > largest )

largest = number[i];

}

return largest;

}

Meaning and Output:

Based on the code provided, the program prompts for the number of elements, takes input for an array, finds the largest value using a function, and prints it. 

Example Output:

text

 Enter total number of elements in the series: 5

 

 Taking input to the array elements:

 Enter element 1: 10

 Enter element 2: 55

 Enter element 3: 2

 Enter element 4: 90

 Enter element 5: 35

 

 Largest number is: 90

 

·         Logic: The user enters 5 as the total elements. The program then accepts five numbers, compares them within find_largest, and outputs the maximum value (90 in this case). 

This C program finds the largest number in a user-defined series (up to 20 integers) using a function. It takes input in main(), passes the total elements to find_largest(), which iterates through the array to identify the maximum value. 

Key Details:

·         Array Size: number[20] restricts input to a maximum of 20 elements.

·         Logic: find_largest initializes largest with the first element and updates it if a larger element is found.

·         Functionality: It properly takes input, calls the function, and prints the result.

·         Limitations: The code does not check if totalEle exceeds 20, which could cause a buffer overflow. 

c

#include<stdio.h>

int find_largest (int);

int number[20]; // Array to store elements

int main()

{

    int totalEle, largest = 0;

    printf("\n Enter total number of elements in the series: ");

    scanf("%d", &totalEle);

    printf("\n Taking input to the array elements: ");

    for(int i=0; i<totalEle; i++)

    {

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

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

    }

    largest = find_largest(totalEle); // Call function to find max

    printf("\n Largest number is: %d", largest);

    return 0;

}

int find_largest( int totalEle)

{

    int largest = number[0]; // Assume first is largest

    for(int i=1; i<totalEle; i++)

    {

        if ( number[i] > largest )

            largest = number[i]; // Update largest

    }

    return largest;

}


 

Example 7.5: A C program for finding the digits of a number using function.

Answer:

#include<stdio.h>

void find_digit(int number)

{

int temp = number, digit = 0;

while(temp > 0)

{

digit = temp % 10;

printf("\n Extracted digit is %d", digit);

temp = temp / 10;

}

}

int main()

{

int number;

printf("Enter the integer: ");

scanf("%d", &number);

find_digit(number);

return 0;

}

 

Meaning and Output

The program extracts digits of an integer in reverse order. For input 123, the output is: 

Enter the integer: 123
Extracted digit is 3
Extracted digit is 2
Extracted digit is 1 

Explanation: The find_digit function uses temp % 10 to get the last digit and temp / 10 to remove it, repeating until 0

 

This C program defines a function find_digit that takes an integer, uses a while loop with modulus (% 10) and division (/ 10) operators to isolate each digit, and prints them in reverse order. The main function prompts the user for an integer input, calls find_digit, and displays the extracted digits one by one. 

 

Key Components:

·         find_digit Function: Extracts digits by taking temp % 10 (last digit) and reduces the number using temp / 10.

·         Loop Condition: Continues until temp becomes 0, meaning all digits are processed.

·         Limitations: This code only works for positive integers; inputting 0 or negative numbers will result in no output or incorrect behavior. 

Example Output:
If the input is 
123, the output will be:

text

Extracted digit is 3

Extracted digit is 2

Extracted digit is 1

 

 


 

Example 7.6: A C program for storing the digits of a number in an array using function.

Answer:

#include<stdio.h>

int digits[10];

int find_digit ( int number )

{

int temp = number, digit = 0, index = 0;

while ( temp > 0 )

{

digit = temp % 10;

printf ( "\n Extracted digit is %d", digit );

digits[index] = digit;

index = index + 1;

temp = temp / 10;

}

return (index-1);

}

int main()

{

int number, lastIndex;

printf ( "Enter the integer: " );

scanf ( "%d", &number );

lastIndex = find_digit ( number );

printf ( "\n Array elements are: \n" );

for ( int i=0; i < = lastIndex; i++ )

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

return 0;

}

Meaning & Output:

It looks like you've written a C program to extract the digits of an integer and store them in an array. However, there is a small issue in the loop where you're printing the array elements:

 

```c

for ( int i=0; i < = lastIndex; i++ )

```

 

The space between `<` and `=` is a typo. It should be `<=` instead of `< =`. Here's the corrected version of the code:

 

```c

#include<stdio.h>

 

int digits[10];  // Array to store digits

 

int find_digit(int number)

{

    int temp = number, digit = 0, index = 0;

    while (temp > 0)

    {

        digit = temp % 10;

        printf("\n Extracted digit is %d", digit);

        digits[index] = digit;

        index = index + 1;

        temp = temp / 10;

    }

    return (index - 1);  // Return the index of the last digit

}

 

int main()

{

    int number, lastIndex;

    printf("Enter the integer: ");

    scanf("%d", &number);

    lastIndex = find_digit(number);

   

    printf("\nArray elements are:\n");

    for (int i = 0; i <= lastIndex; i++)  // Fixed the typo here

    {

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

    }

    return 0;

}

```

 

### Explanation:

 

1. **find_digit function**:

 

   * Extracts the digits of the input integer `number` and stores them in the `digits` array.

   * It uses the modulus operator `%` to extract each digit and the division operator `/` to reduce the number by removing the last digit.

   * It returns the index of the last extracted digit, which will be used to print the digits in the main function.

 

2. **Main function**:

 

   * Reads an integer from the user.

   * Calls the `find_digit` function to extract the digits.

   * Prints the digits in the array.

 

### Sample Output:

 

```

Enter the integer: 12345

 

 Extracted digit is 5

 Extracted digit is 4

 Extracted digit is 3

 Extracted digit is 2

 Extracted digit is 1

 

Array elements are:

5 4 3 2 1

```

 

Let me know if you'd like further explanations or adjustments!

Example 7.7: A C program for displaying the digits of a number in correct order.

Answer:

#include<stdio.h>

int digits[10];

int find_digit ( int number )

{

int temp = number, digit = 0, index = 0;

while ( temp > 0 )

{

digit = temp % 10;

printf ( "\n Extracted digit is %d", digit );

digits[index] = digit;

index = index + 1;

temp = temp / 10;

}

return (index-1);

}

void display_digits(int lastIndex)

{

printf("\n Array elements are: \n");

for ( int i = lastIndex; i >= 0; i-- )

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

}

int main()

{

int number, lastIndex;

printf ( "Enter the integer: " );

scanf ( "%d", &number );

lastIndex = find_digit ( number );

printf ( "\n Array elements are: \n" );

display_digits(lastIndex);

return 0;

}

Meaning & Output

The program extracts individual digits of an integer in reverse order using modulo and division, stores them in an array, and then prints them in the correct order. For input 123, the output shows each extracted digit, then displays them in the original order. 

Example Output (if input is 123):

 

Enter the integer: 123

 

 Extracted digit is 3

 Extracted digit is 2

 Extracted digit is 1

 Array elements are:

 Array elements are:

1 2 3

 

Key Behaviors:

·         Extracted digit: The digits are extracted from right to left (temp % 10).

·         Array storage: The digits are stored in reverse order in digits[].

·         Display: display_digits loops backward from lastIndex to 0, reversing the storage order to print them correctly.

·         Note: The program prints "Array elements are: " twice because it is called in main and again inside display_digits

 

This C program prompts for an integer, extracts its digits in reverse order using modulo/division, stores them in a global array  

digits[10], and displays them in the original order. If 123 is entered, it prints "Extracted digit is 3, 2, 1" and outputs "1 2 3", though it crashes with large numbers (

>10is greater than 10

>10

digits) due to fixed array size. 

Program Analysis 

  • find_digit(int number): Extracts digits from right to left using temp % 10, stores them in digits[index], and returns the lastIndex (total digits - 1).
  • display_digits(int lastIndex): Prints the digits stored in the array from lastIndex down to 0 to reverse them back to the original order.
  • main(): Handles input, calls the functions, and outputs the result.
  • Limitation: The digits[10] array limits input to 10 digits; larger numbers will cause a buffer overflow. It also does not handle negative numbers (while (temp > 0)). 

Example Output (Input: 456) 

 

OUTPUT-2:

Enter the integer: 456

 

 Extracted digit is 6

 Extracted digit is 5

 Extracted digit is 4

 Array elements are:

 Array elements are:

4 5 6

 

 

 

 

Example 7.8: A C program for counting the number of adult persons.

Answer:

#include<stdio.h>

int age[20];

int personCount = 0;

void input()

{

printf ( "\n We are taking inputs in an array \n" );

printf ( "\n How many persons are there? " );

scanf ( "%d", &personCount);

for ( int i = 0; i < personCount; i++ )

{

printf ( "\n Enter age of person %d: ", (i+1) );

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

}

printf ( "\n Input taken \n" );

}

void findAdult()

{

int adultCount = 0;

for ( int i = 0; i < personCount; i++ )

{

if ( age[i] >= 18 )

{

printf( "\n Person %d is an adult ", (i+1) );

adultCount++;

}

else

{

printf( "\n Person %d is NOT an adult ", (i+1) );

}

}

printf("\n Total number of adult persons: %d", adultCount);

}

int main()

{

input();

findAdult();

printf ("\n\n" );

return 0;

}

 

 

 

 

Meaning & Output

This C program calculates the number of adults from a user-defined list of ages. It uses a global array

age[20] to store up to 20 inputs, takes the personCount, iterates through the array to check if each age is

≥18is greater than or equal to 18

≥18

, and prints whether each person is an adult, finally displaying the total count. 

 

Key Code Components:

·         input() function: Prompts for the number of people (personCount) and populates the age array using a for loop.

·         findAdult() function: Iterates through the stored ages, comparing each to 18 to classify them as adults or minors, updating adultCount.

·         main() function: Orchestrates the program flow by calling input() and findAdult().

·         Limitation: The array is fixed at int age[20], meaning it cannot process more than 20 people. 

 

Based on the code provided, the program prompts for the number of people, takes their ages as input, checks if each is 18 or older, and outputs the status of each person followed by the total adult count. 

Assuming an input of 3 people with ages 15, 20, and 18, the output is:

 

 

 We are taking inputs in an array

 

 How many persons are there? 3

 

 Enter age of person 1: 15

 

 Enter age of person 2: 20

 

 Enter age of person 3: 18

 

 Input taken

 

 Person 1 is NOT an adult

 Person 2 is an adult

 Person 3 is an adult

 Total number of adult persons: 2

Example 7.9: A C program for finding the factorial of a number.

Answer:

#include<stdio.h>

int findFacotiral ( int number )

{

int factorial = 1;

while ( number > 0 )

{

factorial = factorial * number;

number = number - 1;

}

return factorial;

}

int main()

{

int number, factorial = 0;

printf ("\n Enter the number: " );

scanf ( "%d", &number );

factorial = findFacotiral ( number );

printf ( "\n Factorial of the number is: %d", factorial );

return 0;

}

 

Meaning & Output

The provided C code calculates the factorial of an integer input by the user. 

Here is the breakdown of the program's execution and output:

Program Description

The code first prompts the user to enter a number. This number is then passed to the findFacotiral function, which iteratively calculates the factorial. Finally, the program prints the result. 

Output

The output depends on the input provided by the user at runtime. 

Scenario 1: User enters a small positive integer (e.g., 5)

If the user enters the number 5 when prompted, the output will be:

text

 Enter the number: 5

 

 Factorial of the number is: 120

Scenario 2: User enters 0

If the user enters the number 0, the while loop condition (number > 0) is immediately false. The function will return the initial value of factorial, which is 1

text

 Enter the number: 0

 

 Factorial of the number is: 1

Note on Integer Overflow

The int data type in C has a limited range. The provided code will produce incorrect results (due to integer overflow) for factorials larger than 12! (13! is larger than the maximum value for a standard 32-bit signed integer). 

For example, if the user enters 13, the output will be a seemingly random or negative number, not the mathematically correct 6,227,020,800. 

 

The provided C code calculates the factorial of an integer input by the user. When the program runs, it first prompts the user for input and then displays the result after the user enters a number.

 

Output Scenarios 

The output will depend entirely on the integer value the user types in when prompted: 

 

User Input (number

Program Output

5

Factorial of the number is: 120

6

Factorial of the number is: 720

10

Factorial of the number is: 3628800

0

Factorial of the number is: 1

Detailed Program Execution Flow 

  1. Prompt: The program prints the message Enter the number: to the console. (Note: The leading \n in the printf statement causes a newline to be printed before the text, if the previous command left the cursor on the same line.)
  2. Input Wait: The program waits for the user to type an integer (e.g., 5) and press Enter.
  3. Calculation: The findFacotiral function is called with the user's number. It uses a while loop to iteratively multiply all positive integers from the input number down to 1.
  4. Result Display: The main function receives the calculated factorial and prints the final output message. 

Potential Issues 

  • Negative Numbers: The current code will enter an infinite loop if the user enters a negative number (e.g., -5), as the condition number > 0 will always be true. The code needs modification to handle negative inputs correctly.

 

·         Large Numbers: Due to the limitations of the int data type, this program can only correctly calculate factorials up to 12! Or 13! (depending on the system’s int size). Any number larger will result in an incorrect output due to integer overflow.


Example 7.10: A C program for finding the factorial of a number using recursion.

Answer:

#include<stdio.h>

int findFacotiral ( int number )

{

if ( number = = 0 )

return 1;

else

return number * findFacotiral ( number - 1 );

}

int main()

{

int number, factorial = 0;

printf ("\n Enter the number: " );

scanf ( "%d", &number );

factorial = findFacotiral ( number );

printf ( "\n Factorial of the number is: %d", factorial );

return 0;

}

 

CHECK & MEANING & OUTPUT

#include <stdio.h>

 

// Function definition must be declared before main to be properly used

int findFactorial(int number) {

    if (number == 0) {

        return 1;

    } else {

        // Recursive call

        return number * findFactorial(number - 1);

    }

}

 

int main() {

    int number, factorial = 0;

    // Removed the incorrect leading comma in the string literal

    printf("\nEnter the number: ");

    // The scanf arguments must be correctly formatted: "%d" is the format specifier

    scanf("%d", &number);

 

    // Call the corrected function name

    factorial = findFactorial(number);

 

    // Removed the incorrect leading comma in the string literal

    printf("\nFactorial of the number is: %d\n", factorial);

 

    return 0;

}

Corrections Made:

1.    Function Name: The original function name was findFacotiral; it has been corrected to findFactorial for proper use within the main function.

2.    printf Statements: The original printf calls used a comma before the string literal (e.g., printf ( \n Enter the number: );), which is a syntax error. Commas are used to separate arguments, but the string literal is the first argument. These commas were removed.

3.    scanf Statement: The original scanf had incorrect formatting (scanf ( %d , &number );). It was corrected to scanf("%d", &number); to adhere to the standard format specifier syntax.

4.    Braces in if/else: While not strictly necessary for single-line statements, braces {} were added around the if and else blocks to improve readability and maintainability.

5.    Function Prototype: Added a function prototype/definition above the main function so the compiler recognizes the function findFactorial before it is called. 

 

Output of the Corrected Code

The output will depend on the number entered by the user.

If the user enters 5:

Enter the number: 5

 

Factorial of the number is: 120

If the user enters 0:

Enter the number: 0

 

Factorial of the number is: 1

 

Exercise

1. What is a global variable in C? Why do we need such a variable?

Answer:

A global variable in C is a variable declared outside of all functions, usually at the beginning of the source file [1]. It has a global scope, meaning it is accessible from any function within the program, across all source files if declared properly [2, 3]. Global variables are stored in the data segment of the program's memory [2]. 

Why We Need Global Variables

We need global variables for several key reasons:

·         Sharing Data Across Functions: The primary reason is to share data among multiple functions without constantly passing the variable as an argument to each function call. This is particularly useful for data that many parts of the program need to access, such as configuration settings or program state [1, 4].

·         Persistent Data: Unlike local variables whose values are lost when the function they are declared in exits (unless declared static), global variables maintain their value throughout the entire execution of the program [3].

·         Convenience: They offer a convenient way to manage values that are constant throughout the program's lifecycle, such as a maximum user limit or a system flag [4].

·         Inter-file Communication: When a large program is split across multiple source files, global variables provide a mechanism for variables in one file to be accessed and modified by functions in another file, using the extern keyword [2, 3]. 

While global variables offer convenience, they can also make a program harder to debug and maintain due to potential side effects and unintended modifications from different parts of the code. Therefore, their use is generally recommended to be limited to scenarios where global access is truly necessary [1, 4]. 

 


 

2. Write the syntax of a function declaration. The name of the function is calculateAge().

The function accepts the current year and birth year of a person. The function returns the age of the person.

Answer:

The syntax for declaring the calculateAge function in C, which accepts the current year and birth year and returns the age, is as follows:

int calculateAge(int currentYear, int birthYear);

Explanation of the syntax:

·         int: This is the return type, specifying that the function will return an integer value (the calculated age).

·         calculateAge: This is the function name.

·         (int currentYear, int birthYear): These are the parameters (also called arguments), enclosed in parentheses.

o    int currentYear: The first parameter is an integer named currentYear.

o    int birthYear: The second parameter is an integer named birthYear.

·         ;: The semicolon at the end signifies that this is a function declaration (or prototype), not the full definition of the function's body. 

 

Full Example (Declaration and Definition):

Here is an example showing the declaration and the subsequent definition of the function within a complete C program:

 

#include <stdio.h>

 

// Function Declaration

int calculateAge(int currentYear, int birthYear);

 

int main() {

    int current, birth, result;

 

    // 1. Ask user for the current year

    printf("Enter the current year: ");

    scanf("%d", &current);

 

    // 2. Ask user for their birth year

    printf("Enter your birth year: ");

    scanf("%d", &birth);

 

    // 3. Call the function and store the returned value

    result = calculateAge(current, birth);

 

    // 4. Display the result

    printf("You are %d years old.\n", result);

 

    return 0;

}

 

// Function Definition

int calculateAge(int currentYear, int birthYear) {

    return currentYear - birthYear;

}

 

Explanation of the above:

To take input from a user in C, you use the scanf function. This requires you to declare variables to store the user's data and then pass those variables as arguments to your calculateAge function.

 

Key Additions Explained

  • scanf("%d", &variable): This is the standard way to get keyboard input.
    • %d tells the compiler to look for an integer.
    • The & (address-of operator) is crucial; it tells scanf exactly where in the computer's memory to store the number you typed.
  • printf: We use this before scanf to act as a "prompt," so the user knows what they are supposed to type.
  • Variables: We created current and birth to hold the data temporarily before sending it to our function.

 

 

Output:

Enter the current year: 2026

Enter your birth year: 1990

You are 36 years old.

 

Explanation of the Output:

1.    Enter the current year: The program prompts for input.

2.    2026 (User input)

3.    Enter your birth year: The program prompts for input.

4.    1990 (User input)

5.    2026 - 1990 The calculateAge function performs the subtraction.

6.    You are 36 years old. The final formatted output. 

 

3. Write the code segment for the function definition of the above function calculateAge().

Answer:

In C programming, the function definition is the actual block of code that contains the logic. While the declaration (prototype) just tells the compiler the function exists, the definition describes how it works.

The Code Segment

Here is the standalone function definition for calculateAge():

C

int calculateAge(int currentYear, int birthYear) {

    int age;

    age = currentYear - birthYear;

    return age;

}


Breakdown of the Definition

·         Return Type (int): Specifies that the function will send back an integer value.

·         Parameters (int currentYear, int birthYear): These are the local variables that receive the values passed from the main() function.

·         Function Body { ... }: Everything inside the curly braces is the logic that executes when the function is called.

·         The Logic: It subtracts the birthYear from the currentYear and uses the return keyword to send the result back to the caller.

Note: You can also write this more concisely as return currentYear - birthYear; without creating the extra age variable inside the function.

Would you like me to help you write a similar function that calculates how many years are left until a specific retirement age?


 

4. What are different types of functions in C? Differentiate among them.

Answer:

Functions in C are primarily categorized into two main types: Library Functions and User-Defined Functions. User-defined functions can be further classified based on whether they use arguments and return values. 

Primary Classification

Aspect 

Library Functions (Predefined)

User-Defined Functions (UDFs)

Definition

Built-in functions, pre-written and stored in C libraries.

Functions written by the programmer for specific tasks tailored to program needs.

Usage

Reused across programs by including the relevant header file (e.g., #include <stdio.h>).

Defined within the program's source code; no special header file is required for their definition.

Customization

Cannot be changed by the user.

Fully customizable; the user defines the logic and behavior.

Examples

printf()scanf()sqrt()strlen().

Functions like calculateSum() or checkPrime() created by a developer for a specific program.

 

Secondary Classification (User-Defined Functions)

User-defined functions are subcategorized based on how data is passed to them (arguments) and how results are sent back to the calling function (return value). 

·         Function with No Arguments and No Return Value:

o    Description: Neither receives data from the calling function nor sends a result back. Communication is minimal or relies on global variables.

o    Use Case: Often used for simple tasks like printing a message or a fixed pattern to the console.

·         Function with Arguments but No Return Value:

o    Description: Receives input (arguments) from the calling function to perform operations, but does not return a value (uses void return type). This is a one-way data communication.

o    Use Case: Performing actions that don't need to pass a result back, such as updating variables via pointers, input validation, or displaying information based on input.

·         Function with No Arguments but a Return Value:

o    Description: Does not accept any input from the calling function but returns a single value after its task is complete.

o    Use Case: Useful for operations that generate a value internally without external input, such as generating a random number or getting system date/time.

·         Function with Arguments and a Return Value:

o    Description: Accepts arguments (input) and performs a task, then returns a single value to the calling function. This allows for a two-way data communication.

o    Use Case: The most common type, used for performing calculations and transformations on given input, such as calculating the area of a rectangle or the factorial of a number. 


5.  Differentiate between caller and callee functions. write a small C progarm and identify the caller and callee function in it.

Answer:

In programming, the fundamental difference between caller and callee functions lies in their relationship during execution: 

·         Caller Function: This is the function that initiates or "calls" another function to perform a specific task. It pauses its own execution and transfers control to the callee.

·         Callee Function: This is the function that is "called" by the caller. It executes the tasks defined within its body and, upon completion, typically returns control and sometimes a value back to the caller function. 

Essentially, one initiates the interaction, and the other responds to and performs the requested operation. 

C Program Example

In the following C program, main() is the caller function, and multiply() is the callee function. 

 

#include <stdio.h>

 

// Definition of the callee function 'multiply'

int multiply(int a, int b) { // <--- This is the CALLEE function

    int result = a * b;

    return result; // Returns the result to the caller

}

 

// Definition of the caller function 'main'

int main() { // <--- This is the CALLER function

    int x = 5;

    int y = 3;

    int product;

 

    // The 'main' function calls 'multiply'

    product = multiply(x, y); // <--- This line is the 'call' operation

 

    printf("The product of %d and %d is: %d\n", x, y, product);

 

    return 0;

}

 

Identification

·         Caller Functionmain()

o    The line product = multiply(x, y); is where main initiates the call to multiply.

·         Callee Functionmultiply()

o    This function receives the inputs a and b, performs the multiplication, and returns the final value to main


 

 

6. When do we call a function user-defined? Is printf() a user-defined function? Justify.

Answer:

A function is called user-defined when it is explicitly declared and defined by the programmer within the source code of a specific program [1]. 

Key characteristics of a user-defined function include:

·         Defined by the programmer: The function's purpose, logic, and implementation are created by the coder to perform a specific task required by their program [1].

·         Contained within the program scope: The source code for the function is written as part of the overall project, unlike built-in functions provided by the language or operating system libraries [1].

·         Customizable: The user can modify the function's behavior, name, parameters, and return type as needed for their specific application [1]. 

The printf() function is not a user-defined function. It is a standard library function provided by the C programming language [1]. 

Justification:

·         printf() is part of the Standard I/O Library (stdio.h) which comes with the C compiler [1].

·         Programmers do not write the source code for printf(); they simply call (use) it within their programs to display formatted output to the console [1].

·         Its implementation is standardized and provided by the system, not created by the individual user for that specific program [1]. The user only needs to include the appropriate header file (e.g., #include <stdio.h>) to access it [1]. 


 

7. Can we have two functions with the same name but with different numbers of parameters in a single C program? Write a simple C program to justify your answer.

Answer:

No, the C programming language does not support function overloading, meaning you cannot have two functions with the same name, even if they have a different number or type of parameters. An attempt to do so in the same scope will result in a compilation error. 

Justification Program

The following C program demonstrates that defining two functions with the same name, display_message, but different numbers of parameters, causes a compilation error. 

 

#include <stdio.h>

 

// Function with one parameter

void display_message(char *message)

{

    printf("Message: %s\n", message);

}

 

// Function with two parameters (This will cause a compilation error)

/*

void display_message(char *message, int num)

{

    printf("Message: %s, Number: %d\n", message, num);

}

*/

 

int main()

{

    char message[] = "Hello, world!";

 

    // Calling the function with one parameter. This is fine.

    display_message(message);

 

    // If the second function were uncommented, a call like

    // display_message(message, 10);

    // would also be a problem as the compiler wouldn't know which one to pick

    // if a single definition was present.

 

    return 0;

}

 

 

Explanation:

When the second display_message function is uncommented and the code is compiled with a C compiler (like GCC), the compiler will issue an error, such as "redefinition of 'display_message'" or "conflicting types for 'display_message'". The C compiler uses only the function name to identify the function at link time and does not perform "name mangling" based on the parameters like a C++ compiler does. 

Workarounds in C

While true function overloading is not a feature of C, similar behavior can be achieved using alternative approaches, such as: 

·         Different Function Names: The most straightforward method is to use distinct names (e.g., display_message_one() and display_message_two()).

·         Variable Arguments: Using the <stdarg.h> library allows a function to accept a variable number of arguments, as the printf() function does.

·         _Generic Selection (C11 standard): This preprocessor macro feature allows the compiler to select a different function based on the type of a single argument at compile time. 


 

8. What are different components of a function? Show with a complete C program.

Answer:

In programming, a function is a self-contained block of code that performs a specific task. Think of it as a "mini-program" within your main program that you can reuse whenever needed.

To use a function properly, you need to understand its four primary components.

1. The Four Components of a Function

·         Function Prototype (Declaration): This tells the compiler about the function's name, return type, and parameters before it is actually used. It usually goes at the top of the file.

·         Function Call: This is the statement used to execute the function. When a program "calls" a function, the control shifts to that function’s definition.

·         Function Header (Definition Start): This is the first line of the actual function code. It must match the prototype's structure.

·         Function Body: The set of statements enclosed in curly braces {} that define what the function actually does.


2. Anatomy of a Function Header

The header itself consists of three vital parts:

1.      Return Type: The data type of the value the function sends back (e.g., int, float, or void if it returns nothing).

2.      Function Name: A unique identifier used to call the function.

3.      Parameters (Arguments): A list of variables (placeholders) that receive data passed into the function.


 

 

 

 

 

 

 

3. Complete C Program Example

Here is a simple program that calculates the area of a rectangle to demonstrate all these components in action.

C

#include <stdio.h>

 

// 1. FUNCTION PROTOTYPE

// Tells the compiler: "There is a function named 'calculateArea' that returns an int"

int calculateArea(int length, int width);

 

int main() {

    int l = 10, w = 5;

    int area;

 

    // 2. FUNCTION CALL

    // Execution jumps from here to the function definition below

    area = calculateArea(l, w);

 

    printf("The area of the rectangle is: %d\n", area);

 

    return 0;

}

 

// 3. FUNCTION HEADER

// Matches the prototype: Return type (int), Name (calculateArea), Parameters (length, width)

int calculateArea(int length, int width) {

   

    // 4. FUNCTION BODY

    // The actual logic of the function

    int result = length * width;

   

    return result; // Returning the value back to the caller

}

Summary Table

Component

Purpose

Location

Prototype

Notifies the compiler of the function's existence.

Above main()

Call

Invokes/starts the function.

Inside main() or another function

Parameters

Passes data into the function.

Inside parentheses ()

Return Value

Sends a result back to the caller.

End of function body

Would you like me to explain the difference between Pass by Value and Pass by Reference using this same example?

 


 

9. Define recursive function. Can we use a recursive function to solve all kinds of problems?

Answer:

A recursive function is a function that calls itself, either directly or indirectly, to solve a problem.

The core idea behind recursion is to break a large, complex problem down into smaller, more manageable sub-problems of the same type. This continues until you reach a "base case"—a simple scenario that can be solved without further recursion.

1. The Two Essential Parts of Recursion

Every recursive function must have two components to work correctly:

·         Base Case: The condition under which the function stops calling itself. Without this, the function would call itself infinitely, eventually leading to a Stack Overflow error.

·         Recursive Step: The part where the function calls itself with a modified (usually smaller) version of the original problem, moving closer to the base case.


2. Can we use recursion for all problems?

Technically, yes, most problems that can be solved with loops (iteration) can also be solved with recursion. However, in practical programming, recursion is not always the best choice.

When Recursion is Great:

·         Problems with a naturally recursive structure: Like calculating Factorials, Fibonacci sequences, or the Tower of Hanoi.

·         Tree/Graph Traversal: Searching through file systems or hierarchical data is much cleaner with recursion.

·         Divide and Conquer Algorithms: Sorting methods like QuickSort or MergeSort rely heavily on recursion.

When Recursion is Bad:

·         Memory Efficiency: Each recursive call adds a new layer (frame) to the system's "stack" memory. If the recursion is too deep, you will run out of memory.

·         Performance: Recursive functions often involve more overhead (function calls, stack management) than simple loops, making them slower for basic tasks.

·         Complexity: If not handled carefully, recursive logic can become harder to debug and read than a standard for or while loop.


 

 

3. Example: Factorial Calculation

Here is a quick comparison of how recursion looks in code versus its mathematical logic.

C

#include <stdio.h>
 
int factorial(int n) {
    // BASE CASE
    if (n <= 1) {
        return 1;
    }
    // RECURSIVE STEP
    else {
        return n * factorial(n - 1);
    }
}
 
int main() {
    int num = 5;
    printf("Factorial of %d is %d", num, factorial(num));
    return 0;
}

 

The output of the code is

Factorial of 5 is 120

The provided C program defines a function factorial that recursively calculates the factorial of an integer 𝑛

 

Code Execution 


Step 1: Initialize variable and call function 

The main function initializes an integer variable num to 5. It then calls the factorial(5) function. 

Step 2: Perform recursive calculation 

The factorial function uses the recursive formula

n!=n×(n−1)!n exclamation mark equals n cross open paren n minus 1 close paren exclamation mark

𝑛!=𝑛×(𝑛−1)!

with a base case

1!=11 exclamation mark equals 1

1!=1

. The calculation resolves as follows:

5!=5×4×3×2×1=1205 exclamation mark equals 5 cross 4 cross 3 cross 2 cross 1 equals 120

5!=5×4×3×2×1=120

Step 3: Print the result 

The printf statement formats the output string using the values of num (5) and the returned factorial value (120). 

Answer: 

The program prints the string Factorial of 5 is 120 to the console. 


10. Consider the below code and list all the syntax errors.

#include<stdio.h>

int fun ( int x )

{

if ( x %2 == 0 )

return 1;

else

return 0;

}

int main()

{

int number;

printf ("\n Enter the number: " );

scanf ( "%d", &number );

int x = fun ( );

return 0;

}

Answer:

In the code provided, there is one primary syntax/compilation error that will prevent the code from running, along with a few "best practice" observations.

1. Missing Argument in Function Call (Critical Error)

The most significant error is in the main function:

C

int x = fun ( );

The function fun is defined as int fun ( int x ), meaning it requires one integer argument. Calling it without passing the variable number will cause a compilation error (specifically, "too few arguments to function").

Corrected line:

C

int x = fun(number);


2. Potential Issues (Depending on Compiler Standards)

While the following might not crash every compiler, they are technically incorrect according to strict C standards:

·         Logic regarding x vs number: Inside main, you declare int x. However, your function parameter is also named x. While C allows this (it's called "shadowing"), it is confusing. More importantly, the variable x in main is being assigned the result of the function, but it is never used.

·         Whitespace in %2: In the line if ( x %2 == 0 ), it is syntactically legal, but standard convention suggests a space: x % 2 == 0.

·         Return Type of main: While return 0; is present, some older C standards prefer int main(void) if no command-line arguments are being used.


Summary Table of Errors

Location

Code

Error Type

Reason

main function

fun ( )

Syntax / Semantic

Function fun expects an int but received nothing.

main function

int x = ...

Logical Warning

Variable x is initialized but never used (Unused Variable).

Here is the corrected version of the program. I have fixed the function call error, addressed the unused variable, and cleaned up the formatting for better readability.

C

#include <stdio.h>

 

// Function definition: checks if a number is even

int fun(int x)

{

    if (x % 2 == 0)

        return 1; // Returns 1 for True (Even)

    else

        return 0; // Returns 0 for False (Odd)

}

 

int main()

{

    int number;

   

    printf("\n Enter the number: ");

    // Ensure the input is captured correctly

    if (scanf("%d", &number) != 1) {

        printf("Invalid input. Please enter an integer.\n");

        return 1;

    }

 

    // CORRECTED: Passed 'number' as an argument to 'fun'

    int result = fun(number);

 

    // Using the returned value to provide feedback to the user

    if (result == 1) {

        printf("The number %d is Even.\n", number);

    } else {

        printf("The number %d is Odd.\n", number);

    }

 

    return 0;

}


Key Improvements Made:

·         Fixed Function Call: Changed fun() to fun(number). In C, if a function is defined with a parameter, you must provide a matching argument when calling it.

·         Renamed Variable x: In main, I changed the variable name from x to result. This avoids confusion with the x used as a parameter inside the fun function.

·         Added Output Logic: I added an if-else statement in main so that the program actually tells the user the result of the calculation.

·         Input Validation: Added a small check to ensure scanf actually receives a valid number, which prevents the program from behaving unpredictably with text input.

How the "Fix" Works in Memory

When you call fun(number), the program creates a "stack frame." It copies the value of number from main into the variable x in fun. The function performs the math, returns the answer, and then that stack frame is destroyed, returning control to main.

Would you like me to explain how to rewrite the fun function using a more concise ternary operator to make the code shorter?

 

11. Consider the code segment below and find out the output if the user enters 5 from the keyboard when asked for.

 

#include<stdio.h>

int fun ( int x )

{

if ( x %2 == 0 )

return 1;

else

return 0;

}

int main()

{

int number;

printf ("\n Enter the number: " );

scanf ( "%d", &number );

int x = fun ( number);

printf("%d", x);

return 0;

}

 

Answer:

 

The output when the user enters 5 will be 0

 

If the user enters 5 from the keyboard, the output of the program will be 0.

Step-by-Step Execution:

1.      Input: The scanf function assigns the value 5 to the variable number.

2.      Function Call: The program calls fun(5).

3.      Conditional Check: Inside the function fun, it evaluates the condition:

o    5 (mod 2) = = 0

o    Since 5 divided by 2 leaves a remainder of 1, the condition 1 = = 0 is False.

4.      Return Value: Because the if condition failed, the function executes the else block and returns 0.

5.      Output: Back in main, the variable x becomes 0, and printf("%d", x) prints 0 to the screen.


Understanding the Logic

This specific function acts as an Even/Odd checker.

·         It returns 1 (True) if the number is Even.

·         It returns 0 (False) if the number is Odd.

Since 5 is an odd number, the result is 0.

Would you like me to show you how to modify this code so it prints the words "Even" or "Odd" instead of just 1 or 0?

 

 


 

12. Write a C program and define a function square() that accepts a number as the parameter and returns the square of that number as output.

 

Answer:

To create this program, we will define a function that takes an integer as an input, multiplies it by itself, and returns the result to the main() function.

C Program to Calculate Square

C

#include <stdio.h>

 

// Function Prototype

int square(int num);

 

int main() {

    int input, result;

 

    printf("Enter a number to find its square: ");

    scanf("%d", &input);

 

    // Calling the function and storing the return value in 'result'

    result = square(input);

 

    printf("The square of %d is: %d\n", input, result);

 

    return 0;

}

 

// Function Definition

int square(int num) {

    // The function returns the number multiplied by itself

    return (num * num);

}


How the Data Flows

In this program, the data moves through the different components we discussed earlier:

1.      Parameter Passing: When you call square(input), the value of input is copied into the local variable num inside the function.

2.      Processing: The function calculates $num \times num$.

3.      Returning: The return keyword sends that product back to the main() function, where it is assigned to the variable result.

Key Components Used:

·         Return Type: int (because the square of an integer is an integer).

·         Parameter: int num (the number being sent to the function).

·         Return Statement: return (num * num); (this exits the function and provides the answer).

Would you like to see how to modify this to use float or double so it can handle decimal numbers as well?

 

 


 

13. Write a C program and define a function search() that searches an element in an array and returns the index of the element.

Answer:

To solve this, we will use a Linear Search algorithm. This approach involves a function that loops through each element of the array and compares it to the target value.

C Program: Searching for an Element

C

#include <stdio.h>

 

// Function Prototype

// Returns the index if found, or -1 if the element does not exist

int search(int arr[], int size, int target);

 

int main() {

    int my_array[] = {12, 45, 7, 19, 23, 56};

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

    int key, result;

 

    printf("Enter the number you want to search for: ");

    scanf("%d", &key);

 

    // Function Call

    result = search(my_array, n, key);

 

    if (result != -1) {

        printf("Element found at index: %d\n", result);

    } else {

        printf("Element not found in the array.\n");

    }

 

    return 0;

}

 

// Function Definition

int search(int arr[], int size, int target) {

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

        // Check if the current element matches the target

        if (arr[i] == target) {

            return i; // Return the current index and exit function

        }

    }

   

    // If the loop finishes without returning, the element isn't there

    return -1;

}


 

 

How the Search Function Works

·         Parameters: The function takes three pieces of information: the array itself (arr[]), the number of elements in it (size), and the value we are looking for (target).

·         The Loop: We use a for loop to visit every index from 0 to size - 1.

·         Early Exit: As soon as arr[i] == target is true, the return i; statement executes. This immediately stops the function and sends the index back to main.

·         The Sentinel Value (-1): If the loop completes and nothing is found, we return -1. This is a common practice in programming because -1 is not a valid array index, so it clearly signals "Not Found."


Important Considerations

·         Array Size: In C, when you pass an array to a function, the function doesn't automatically know how big it is. That is why we must pass the size as a separate parameter.

·         Efficiency: This function has a Time Complexity of O(n), meaning in the worst case (if the item is at the very end or missing), it has to check every single element.

Would you like me to show you how to perform a Binary Search, which is much faster but requires the array to be sorted first?

 


 

14. Write a C program and define a recursive function to find the summation of first N natural numbers.

Answer:

#include <stdio.h>

 

/*

 * Recursive function to calculate the summation of the first N natural numbers.

 */

int sum_natural_numbers(int n) {

    // Base case: if n is 1, the sum is 1.

    if (n == 1) {

        return 1;

    }

    // Recursive step: return the current number plus the sum of all previous numbers.

    else {

        return n + sum_natural_numbers(n - 1);

    }

}

 

int main() {

    int N;

   

    // Prompt the user for input

    printf("Enter a positive integer N to find the summation of the first N natural numbers: ");

   

    // Read the input

    if (scanf("%d", &N) != 1 || N <= 0) {

        printf("Invalid input. Please enter a positive integer.\n");

        return 1; // Exit with an error code

    }

 

    // Call the recursive function and store the result

    int total_sum = sum_natural_numbers(N);

 

    // Print the result

    printf("The summation of the first %d natural numbers is: %d\n", N, total_sum);

 

    return 0;

}

 

 

 

 

 

 

 

How the program works:

1.    sum_natural_numbers(int n) function:

·         Base Case: The function checks if n is equal to 1. If it is, the recursion stops, and it returns 1. This is crucial to prevent infinite recursion.

·         Recursive Step: If n is greater than 1, the function returns the sum of the current n and the result of calling itself with n - 1. This process repeats until the base case (n == 1) is reached.

                main() function:

·         It prompts the user to enter a number N.

·         It validates the input to ensure it's a positive integer.

·         It calls the sum_natural_numbers function with the provided N and prints the final calculated sum. 

 

 


 

15. Write a C program and define a function add() that accepts three integers. These integers indicate indices of an integer array. The function returns the summation of the elements stored in those indices.

 

7

8

8

0

0

9

 

For example, if we call the function add( 0, 2, 5), the function will return 24. The output is formed by 7 + 8 + 9 because elements at indices 0, 2 and 5 are 7, 8 and 9 respectively.

 

Answer:

Here's a C program that defines a function `add()` to accept three integers as indices of an array and returns the summation of the elements stored at those indices.

 

### Code:

 

```c

#include <stdio.h>

 

// Function that returns the sum of elements at three indices in an array

int add(int index1, int index2, int index3, int arr[]) {

    return arr[index1] + arr[index2] + arr[index3];

}

 

int main() {

    // Declare and initialize the array

    int arr[] = {7, 8, 8, 0, 0, 9};

   

    // Declare variables for the indices

    int index1, index2, index3;

   

    // Prompt the user for indices

    printf("Enter three indices: ");

    scanf("%d %d %d", &index1, &index2, &index3);

   

    // Call the add() function and print the result

    int result = add(index1, index2, index3, arr);

    printf("The sum of the elements at indices %d, %d, and %d is: %d\n", index1, index2, index3, result);

   

    return 0;

}

```

 

### Explanation:

 

1. **add() function**:

 

   * The function accepts three integer indices (`index1`, `index2`, `index3`) and an array `arr[]`.

   * It returns the sum of the elements at those three indices in the array.

 

2. **Main function**:

 

   * Initializes the array `arr[]` with the values `{7, 8, 8, 0, 0, 9}`.

   * Asks the user to input three indices.

   * Calls the `add()` function to get the sum of the elements at the given indices and prints the result.

 

### Sample Output:

 

```

Enter three indices: 0 2 5

The sum of the elements at indices 0, 2, and 5 is: 24

```

 

### Explanation of Example:

 

For indices `0`, `2`, and `5`:

 

* Element at index `0` = 7

* Element at index `2` = 8

* Element at index `5` = 9

 

The sum = `7 + 8 + 9 = 24`.

 

Let me know if you'd like to explore anything further!