Read Principal, Rate, Time
In this step, you will learn how to read the principal, rate, and time for calculating simple interest in a C program. We'll create a program that prompts the user to input these financial parameters.
First, let's create a new C file in the ~/project
directory:
cd ~/project
nano simple_interest.c
Now, enter the following code to read the principal, rate, and time:
#include <stdio.h>
int main() {
float principal, rate, time;
// Prompt user to input principal amount
printf("Enter the principal amount: ");
scanf("%f", &principal);
// Prompt user to input interest rate
printf("Enter the annual interest rate (%): ");
scanf("%f", &rate);
// Prompt user to input time period
printf("Enter the time period (in years): ");
scanf("%f", &time);
// Print the input values
printf("\nInput Values:\n");
printf("Principal: $%.2f\n", principal);
printf("Interest Rate: %.2f%%\n", rate);
printf("Time Period: %.2f years\n", time);
return 0;
}
Compile and run the program:
gcc simple_interest.c -o simple_interest
./simple_interest
Example output:
Enter the principal amount: 1000
Enter the annual interest rate (%): 5
Enter the time period (in years): 2
Input Values:
Principal: $1000.00
Interest Rate: 5.00%
Time Period: 2.00 years
Explanation
- We use
float
data type to store decimal values for principal, rate, and time
printf()
is used to display prompts and instructions to the user
scanf()
reads user input for each variable
%.2f
format specifier displays floating-point numbers with 2 decimal places