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.
#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:
float addFunc(float *a, float *b)
- This line declares a function named
addFuncthat takes two float pointers (aandb) as parameters and returns a float value.
Function Definition:
{ float sum; sum = *a + *b; return sum; }
- Inside the
addFuncfunction, it calculates the sum of the values pointed to byaandband returns the result.
Main Function:
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
mainfunction is the entry point of the program. - It declares three float variables
num1,num2, andresult. - It takes user input for
num1andnum2usingscanf. - Calls the
addFuncfunction, passing the addresses ofnum1andnum2. - 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
addFuncfunction. - Finally, it prints the result to the console.
So, if the user enters, for example, 5.3 and 2.7, the program would output:
Enter the first number: 5.3
Enter the Second number: 2.7
Sum of the result: 8.000000