The program takes the two numbers from the user and passes the reference to the function where the sum is calculated. You may go through the topic below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | #include <stdio.h> //user-defined function float addFunc(float *a, float *b) { float sum; sum = *a + *b; return sum; } int main() { float num1, num2, result; printf("Enter the first number: "); scanf("%f", &num1); printf("Enter the Second number: "); scanf("%f", &num2); result = addFunc(&num1, &num2); printf("Sum of the result: %f", result); return 0; } |
Output:
Enter the first number: 15.5
Enter the Second number: 20.5
Sum of the result: 36.000000
This is a simple C program that demonstrates the use of a user-defined function to add two floating-point numbers. Let’s break down the code:
Function Declaration:
1 | <code>float addFunc(float *a, float *b)</code> |
- This line declares a function named
addFunc
that takes two float pointers (a
andb
) as parameters and returns a float value.
Function Definition:
1 | <code>{ float sum; sum = *a + *b; return sum; }</code> |
- Inside the
addFunc
function, it calculates the sum of the values pointed to bya
andb
and returns the result.
Main Function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | int main() { // Variable declaration float num1, num2, result; // Input from user printf("Enter the first number: "); scanf("%f", &num1); printf("Enter the Second number: "); scanf("%f", &num2); // Function call result = addFunc(&num1, &num2); // Output printf("Sum of the result: %f", result); return 0; } |
- The
main
function is the entry point of the program. - It declares three float variables
num1
,num2
, andresult
. - It takes user input for
num1
andnum2
usingscanf
. - Calls the
addFunc
function, passing the addresses ofnum1
andnum2
. - Prints the result.
Execution:
- The program prompts the user to enter two floating-point numbers.
- It then calculates the sum of these numbers using the
addFunc
function. - Finally, it prints the result to the console.
So, if the user enters, for example, 5.3
and 2.7
, the program would output:
1 2 3 | Enter the first number: 5.3 Enter the Second number: 2.7 Sum of the result: 8.000000 |