This code is a C program that calculates the average of two numbers input by the user. It begins by including the standard input-output library, stdio.h
.
#include <stdio.h>
int main()
{
int first_number, second_number;
float average;
printf("Enter first number: ");
scanf("%d", &first_number);
printf("Enter second number: ");
scanf("%d", &second_number);
average = (float)(first_number + second_number)/2;
printf("Average of %d and %d is: %.2f", first_number, second_number, average);
return 0;
}
Result:
Enter first number: 10
Enter second number: 5
Average of 10 and 5 is: 7.50
Process returned 0 (0x0) execution time : 5.174 s
Press any key to continue.
The main()
function is then declared, which returns an integer value. Inside the function, three variables are declared - two integers first_number
and second_number
to hold the user input values, and a float average
to hold the average value.
The program then uses the printf()
function to display a prompt message asking the user to enter the first number. The scanf()
function is used to read the integer input value from the user and store it in the first_number
variable. Similarly, the program prompts the user to enter the second number, reads the input value and stores it in the second_number
variable using scanf()
.
Next, the program calculates the average of the two numbers by adding them together and dividing the sum by 2. Since we want the average to be in decimal form, we use typecasting to convert one of the integers to a float value before performing the division. The result is stored in the average
variable.
Finally, the program uses printf()
function again to display the average value with two decimal places. The values of first_number
, second_number
, and average
are passed as arguments to printf()
using format specifiers %d
and %f
. The specifier .2
before f
is used to specify that the number should be displayed with two decimal places.
The return 0
statement at the end of the function indicates that the program has completed successfully.
No comments:
Post a Comment