Read Values and Probabilities
In this step, you'll learn how to read values and probabilities for computing the expected value of a discrete distribution in C. We'll create a program that allows users to input multiple values and their corresponding probabilities.
First, let's create a new C file in the ~/project
directory:
cd ~/project
nano expected_value.c
Now, let's write the initial code to read values and probabilities:
#include <stdio.h>
#define MAX_OUTCOMES 10
int main() {
double values[MAX_OUTCOMES];
double probabilities[MAX_OUTCOMES];
int num_outcomes;
printf("Enter the number of outcomes (max %d): ", MAX_OUTCOMES);
scanf("%d", &num_outcomes);
// Input values
printf("Enter the values:\n");
for (int i = 0; i < num_outcomes; i++) {
printf("Value %d: ", i + 1);
scanf("%lf", &values[i]);
}
// Input probabilities
printf("Enter the probabilities:\n");
for (int i = 0; i < num_outcomes; i++) {
printf("Probability %d: ", i + 1);
scanf("%lf", &probabilities[i]);
}
// Print input for verification
printf("\nInput Values:\n");
for (int i = 0; i < num_outcomes; i++) {
printf("Value %d: %.2f, Probability %d: %.2f\n",
i + 1, values[i], i + 1, probabilities[i]);
}
return 0;
}
Compile and run the program:
gcc expected_value.c -o expected_value
./expected_value
Example output:
Enter the number of outcomes (max 10): 3
Enter the values:
Value 1: 10
Value 2: 20
Value 3: 30
Enter the probabilities:
Probability 1: 0.2
Probability 2: 0.5
Probability 3: 0.3
Input Values:
Value 1: 10.00, Probability 1: 0.20
Value 2: 20.00, Probability 2: 0.50
Value 3: 30.00, Probability 3: 0.30
Key points to understand:
- We use arrays to store values and probabilities
MAX_OUTCOMES
defines the maximum number of possible outcomes
scanf()
is used to read user input for values and probabilities
- We print the input to verify correct data entry