I have a program simulating a BMI (Body Mass Index) Calculator that takes in inputs from 10 users asking each user for a weight and a height, the program then calculates the BMI and prints the result of the computation in a formatted output.
Something like this:
USER BMI STATUS
1
:
10
So I thought of this, I would take in the inputs from the users first, then try to display the computation of the inputs in the above formatted way. Here's what I've tried to come up with which keeps asking the users for their weight and height until the 10th user.
#include <stdio.h>
#include <math.h>
int main(void) {
float weight_value = 0.0f;
float user_height = 0.0f;
float BMI = 0.0f;
char BMI_Status[30];
int i;
for ( i = 1; i <= 10; i++)
{
printf("Please enter your weight: ");
scanf("%f", &weight_value); //Reads in the user's weight
printf("Now enter your height: ");
scanf("%f", &user_height); //Reads in the user's height
BMI = weight_value / (user_height * user_height);
}
return 0;
}
The BMI Status is a string that displays different states of the computed BMI values, which are "Underweight", "Normal", "Overweight" for when the BMI value is within a given range.
The code snippet above is still incomplete as I'm still finding it difficult to add the rest of the code. Here are the issues I'm trying to solve.
How can I print out the BMI values after I have taken in the 10 inputs?
I have tried having a nested for loop that prints out the values, but this is illogical as there will now be an output of the BMI for every iteration of the outer for loop, so I'm guessing need a way to make scanf() hold the BMI values after the for loop's block.
How do I make the status strings appear?
I know there's no string datatype in C, so I'll have to declare a char array that holds the string for the status, but these are different strings for different statuses, and it has to be printed out for every line. I thought of having if else if else conditions for this but I just can't get the char array to work.
I already successfully wrote a code that prints out the user's BMI at every iteration, but this isn't how its supposed to be done.
Another thing I thought of was keeping the BMI values in an array of floating point numbers then displaying the values from the array in the above formatted way, but I'm still a bit sceptical about how I intend doing this.
Here the complete code to display the use of arrays to store the values. Your idea of using an if else for displaying how overweight a person is was good and so I implemented it.
#include <stdio.h>
#include <math.h>
int main(void) {
float weight_value[10]; //two arrays of ten elements each
float user_height[10];
float BMI = 0.0f;
char BMI_Status[30];
int i;
for ( i = 0; i < 10; i++) //the array starts from zero in C
{
printf("Please enter your weight: ");
scanf("%f", &weight_value[i]); //store the values in the array
printf("Now enter your height: ");
scanf("%f", &user_height[i]); //store the values in the array
}
printf("USER BMI\t\tSTATUS\n");
for( i = 0; i < 10; i++) //pass the array once again and calculate the needed values
{
BMI = weight_value[i] / (user_height[i] * user_height[i]);
printf("%d\t%f\t", i+1, BMI);
if(BMI < 30)
printf("Underweight\n");
else if(BMI < 50)
printf("Normal\n");
else
printf("Overweight\n");
}
return 0;
}
edited: skip to last
you will need to save them somewhere before you can read them to display it, you need to use an array to store all 10 inputs, at the moment every time a user inputs a data it will rewrite the data that was in the variable, which had the last user's data.
it needs to look like this:
...
float weight_value[10];
float user_height[10];
float BMI =[10];
char BMI_Status[30][3];
for ( int i = 1; i <= 10; i++)
{
printf("Please enter your weight: ");
scanf("%f", &weight_value[i]); //Reads in the user's weight
printf("Now enter your height: ");
scanf("%f", &user_height[i]); //Reads in the user's height
BMI[i] = weight_value / (user_height * user_height);
}
...
then to display you will need a loop like this
...
printf("user \t weight \t height \t BMi");
for ( int i = 1; i <= 10; i++)
{
printf("%d \t%f \t%f \t%s ", i,user_weight[i],user_height[i],BMI[i]);
}
...
i just re-read the question and realised i misread, however the last bit shows how you can read them from the array and display them.
The following code will store the weight and height of 4 users and print their BMI for an arbitrary number of thresholds (set to two in this case).
You can solve problem 1. by storing the weight and height into arrays (in the first loop).
You can then display a BMI status string by first defining a set of thresholds and a corresponding status string. In the second loop, for every user you compute and check whether the BMI value is under a given threshold and print its corresponding status string.
#include <stdio.h>
#include <math.h>
#include <stdbool.h>
#define USERS 4
#define THRESHOLDS 2
int main(void) {
float weight[USERS];
float height[USERS];
float BMI = 0.0f;
char * BMI_Status[THRESHOLDS+1] = {"Normal","Overweight","Obese"};
float thresholds[THRESHOLDS] = {10.0,20.0};
int i,j;
for ( i = 0; i < USERS; i++)
{
printf("Please enter your weight: ");
scanf("%f", &(weight[i])); //Reads in the user's weight
printf("Now enter your height: ");
scanf("%f", &(height[i])); //Reads in the user's height
}
for ( i = 0; i < USERS; i++)
{
BMI = weight[i]/(height[i]*height[i]);
printf("%d\t%f\t",i,BMI);
for ( j = 0 ; j < THRESHOLDS ; j++ ){
if ( BMI < thresholds[j]){
break;
}
}
printf("%s\n",BMI_Status[j]);
}
return 0;
}
Add an if statement in the for-loop
float BMI[10];
int j;
for ( i = 1; i <= 10; i++)
{
printf("Please enter your weight: ");
scanf("%f", &weight_value); //Reads in the user's weight
printf("Now enter your height: ");
scanf("%f", &user_height); //Reads in the user's height
BMI[i-1] = weight_value / (user_height * user_height);
if (i==10)
for (j=0; j<10; j++)
printf ("%d\n", BMI[j]);
}
Use char **a or char *a[]
for example:
char s[12] = "Hello World!";
char *p;
p = &s[0];
char *BMI_Status[30]; //declare 30 char*
BMI_Status[0] = "Fat";
BMI_Status[1] = "Thin";
...
//output
printf ("%s", BMI_Status[0]); //Fat
Related
I have written a program to calculate compound interest.
Here is the code:
#include <stdio.h>
#include <math.h>
int main(void) {
float value, rate, years,r;
int column = 0, tmp;
printf("Enter money values: ");
scanf("%f",&value);
printf("Enter a interest rate: ");
scanf("%f",&rate);
printf("Enter number of years: ");
scanf("%f",&years);
printf("\nYears ");
tmp = rate + 4;
r = rate;
for (int a = rate; a <= tmp; a++) {
printf(" %d ", a);
column++;
}
for (int b = 1; b <= column; b++) {
printf("\n %d",b);
for (int i = 1; i<= column; i++) {
printf(" %.2f ", (float) pow ( (value)*(1.0+((r/100.0)/(1.0))) , (1.0*b))
r++;
}
r = rate;
printf("\n");
}
// I = P*R*T
// P= AMOUNT (value)
// R=RATE (r)
// T=YEARS (b)
return 0;
}
It asks the user for a value (money), interest rate, number of years and displays the interest rate like so:
Enter money values: 100
Enter a interest rate: 6
Enter number of years: 5
Years 6 7 8 9 10
1 106.00 107.00 108.00 109.00 110.00
2 11236.00 11449.00 11664.00 11881.00 12100.00
3 1191016.00 1225043.00 1259712.00 1295029.00 1331000.00
4 126247696.00 131079600.00 136048896.00 141158160.00 146410000.00
5 13382255616.00 14025517056.00 14693280768.00 15386240000.00 16105100288.00
But my problem is the floating point calculation.
As you may be able to tell the numbers in the output above and very long and have many trailing digits
which i am very confused about.
For example in the 2nd row the first output is 11236.00,
this is wrong since it should be outputting 112.36 but for some reason the decimal has moved
forward two spaces. Why is this? and how could i fix this problem and print the correct solution
with the decimal in the correct place.
You have the value inside the pow. So when you square for two years, you are squaring the amount. Move the (value)* to output the pow call.
Hello I have been working on a program in C that calculates numbers and it gives me back an average. Now I'm having issues implementing code that will ask a user to enter any number of pairs and calculate the average. Below is the code that I been working on. I'm able to change the while (count < 5)to 10 to get more pairs, but my goal is to ask a user to input any PAIR and THEN calculate the average (re iterating).
#include <stdio.h>
int main () {
int count;
double avg, value, weight, sum, sumw;
count = 0;
sum = 0;
sumw = 0;
avg = 0.0;
while (count < 5) {
printf("Enter value and it's weight:");
scanf("%lf %lf", &value, &weight);
if (weight >= 0) {
sumw = sumw + weight;
sum = sum + value * weight;
count = count + 1;
}
else { printf("weight must be positive\n");
}
}
avg = sum / sumw;
printf("average is %lf\n " , avg );
return 0;
}
**Second part ** On this on I'm not too sure how to make it to PAIRS plus calculate avg. ej: 2 1 , 2 4 , 4 4 etc.
#include<stdio.h>
void main()
{
int i,n,Sum=0,numbers;
float Average;
printf("\nPlease Enter How many pairs do you want?\n");
scanf("%d",&n);
printf("\nPlease Enter the elements one by one\n");
for(i=0;i<n;++i)
{
scanf("%d",&numbers);
Sum = Sum +numbers;
}
Average = Sum/n;
printf("\nAverage of the %d Numbers = %.2f",n, Average);
return 0;
}
but my goal is to ask a user to input any PAIR and THEN calculate the
Well, then you need to store the values somewhere. Recommendation: Have a struct for:
typedef struct
{
double value;
double weight;
} Pair;
Then as soon as you have got number of pairs to read from user, create an array of pairs:
Pair* pairs = malloc(number * sizeof(*pairs));
Very important: Every malloc should go with a free to avoid memory leaks. General recommendation: plan the free immediately when or even before mallocing.
Now inside your loop, you can fill the pairs:
scanf("%lf %lf", &pairs[i].value, &pairs[weight].weight);
Analogously, you can then use the pairs in the array in next loop or for whatever other purpose.
Side note:
if (weight >= 0)
{
// ...
}
else
{
// printf("weight must be positive\n");
}
If user gave negative input, you'll be just skipping some values (or or as in loop proposed, still retain the negative values!).
You might instead read inside a nested loop until value is valid. Additionally consider user providing non-numeric input, too! In that case, you couldn't read a double at all. So general rule is: Always check the result of scanf:
if(scanf("%lf %lf", &value, &weight) != 2 || value < 0 || weight < 0)
// ^
// assuming negative value not desired either
{
// user input was invalid!!!
}
disclaimer: I'm new to programming
I'm working on this problem
so far ive written this which takes user inputs and calculates an average based on them
#include <stdio.h>
int main()
{
int n, i;
float num[100], sum = 0.0, average;
for(i = 0; i < n; ++i)
{
printf("%d. Enter number: ", i+1);
scanf("%f", &num[i]);
sum += num[i];
}
average = sum / n;
printf("Average = %.2f", average);
return 0;
}
I'd like the user to enter -1 to indicate that they are done entering data; I can't figure out how to do that. so if possible can someone explain or give me an idea as to how to do it
Thank you!
#include <stdio.h>
int main()
{
int i = 0;
float num[100], sum = 0.0, average;
float x = 0.0;
while(1) {
printf("%d. Enter number: ", i+1);
scanf("%f", &x);
if(x == -1)
break;
num[i] = x;
sum += num[i];
i++;
}
average = sum / i;
printf("\n Average = %.2f", average);
return 0;
}
There is no need for the array num[] if you don't want the data to be used later.
Hope this will help.!!
You just need the average. No need to store all the entered numbers for that.
You just need the number inputs before the -1 stored in a variable, say count which is incremented upon each iteration of the loop and a variable like sum to hold the sum of all numbers entered so far.
In your program, you have not initialised n before using it. n has only garbage whose value in indeterminate.
You don't even need the average variable for that. You can just print out sum/count while printing the average.
Do
int count=0;
float num, sum = 0;
while(scanf("%f", &num)==1 && num!=-1)
{
count++;
sum += num;
}
to stop reading at -1.
There is no need to declare an array to store entered numbers. All you need is to check whether next entered number is equal to -1 and if not then to add it to the sum.
Pay attention to that according to the assignment the user has to enter integer numbers. The average can be calculated as an integer number or as a float number.
The program can look the following way
#include <stdio.h>
int main( void )
{
unsigned int n = 0;
unsigned long long int sum = 0;
printf("Enter a sequence of positive numbers (-1 - exit): ");
for (unsigned int num; scanf("%u", &num) == 1 && num != -1; )
{
++n;
sum += num;
}
if (n)
{
printf("\nAverage = %llu\n", sum / n);
}
else
{
puts("You did not eneter a number. Try next time.");
}
return 0;
}
The program output might look like
Enter a sequence of positive numbers (-1 - exit): 1 2 3 4 5 6 7 8 9 10 -1
Average = 5
If you need to calculate the average as a float number then just declare the variable sum as having the type double and use the corresponding format specifier in the printf statement to output the average.
I have asked for the user to enter in several values to calculate an average, however I'd like to also calculate a gradient which uses the inputted values. How do I name these values so I can use them again? Thank you.
Here is what I have thus far:
#include <stdio.h>
int main () {
int n, i;
float num[1000], total=0, mean;
printf("Enter the amount of x-values:");
scanf("%d", &n);
while (n <= 0 || n > 1000) {
printf("Print error. The number should in range of 0 to 1000.\n");
printf("Please try to enter the amount again: ");
scanf("%d", &n);
}
for (i = 0; i < n; ++i) {
printf("%d. Input x-value:", i+1);
scanf("%f", &num[i]);
total += num[i];
}
mean=total/n;
printf("The mean of all the x-values entered is %.2f to 2 decimal places", mean);
{
float num[1000], total=0, mean;
printf("Enter the amount of y-values:");
scanf("%d", &n);
while (n <= 0 || n > 1000) {
printf("Print error. The number should in range of 0 to 1000.\n");
printf("Please try to enter the amount again: ");
scanf("%d",&n);
}
for (i = 0; i < n; ++i) {
printf("%d. Input y-value:", i+1);
scanf("%f", &num[i]);
total += num[i];
}
mean = total / n;
printf("The mean of all the y-values entered is %.2f to 2 decimal places", mean);
return 0;
}
}
Naming the variable is really up to you, but `int gradient[NUM_ELEMENTS]; seems appropriate. It is an array, which also seems appropriate if it's purpose is to assist in finding the gradient from a series of numbers.
Steps could be:
1) use printf to ask user for values, specify spaces or commas between values. You can also specify a limit of values. Example printf("enter 5 numbers separated by commas\n:");
2) use scanf or similar to read values from standard input (the terminal) into the array: scanf("%d,%d,%d,%d,%d", &gradient[0], &gradient[1], &gradient[2], &gradient[3], &gradient[4]);
3) use the array an a function that will compute the gradient.
Simple example:
(where gradient computation, error checking, bounds checking etc. is all left to you)
int get_gradient(int a[5]);
int main(void) {
int gradient[5];
int iGradient=0;
printf("enter 5 numbers separated by commas");
scanf("%d,%d,%d,%d,%d", &gradient[0], &gradient[1], &gradient[2], &gradient[3], &gradient[4]);
iGradient = get_gradient(gradient);
return 0;
}
int get_gradient(int a[5])
{
return [do computation here using array a];
}
Edit:
The above example works only if you know the number of elements at compile time. It uses an int array that has been created on the stack. If you do not know how big of an array you will need until run-time, for example if user input determines the size, then the array size needs to be determined at run-time. One options is to create the variable needed on the heap. (read about stack and heap here) The following uses some techniques different from the simpler version above to get user input, including a function I called get_int(), which uses scanf() in conjunction with strtol(). Here's the example:
int main(void) {
char input[80]={0};
char **dummy={0};
long *gradient = {0};
int iGradient=0;
int arraysize;
int i;
char* fmt = "%[^\n]%*c";
printf("how many numbers will be entered?");
scanf(fmt, input);
arraysize = strtol(input, dummy, 10);
gradient = calloc(arraysize, sizeof(long));
if(gradient)
{
for(i=0;i<arraysize;i++)
{
gradient[i] = get_int();
}
iGradient = get_gradient(gradient, arraysize);
//free gradient when done getting result
free(gradient);
}
return 0;
}
int get_gradient(int *a, int num)
{
int grad = 0, i;
//do something here to compute gradient
return grad;
}
long get_int(void)
{
char input[80]={0};
char **dummy={0};
char* fmt = "%[^\n]%*c";
printf("Enter integer number and hit return:\n");
scanf(fmt, input);
return strtol(input, dummy, 10);
}
I have a loop that prints out different BMI values for 10 users in this format:
USER BMI STATUS
1
:
10
The BMI Statuses are strings "Overweight", "Normal" , "Underweight", and "Obese"
Underweight - When the BMI is less than 18.50
Normal - When the BMI is from 18.50 to 24.9
Overweight - When the BMI is from 25.0 to 29.9
Obese - When the BMI is greater than 30.0
I already figured out how to print out the BMI values on new lines from the awesome answers I got here but I'm still finding it hard to display the BMI Statuses.
Here's what I have,
#include <stdio.h>
#include <math.h>
int main(void) {
float weight_value[10];
float user_height[10];
float BMI = 0.0f;
char* BMI_Status[] = {"Underweight", "Normal", "Overweight", "Obese"};
int i;
for ( i = 0; i < 10; i++ )
{
printf("Please enter your weight: ");
scanf("%f", &weight_value[i]); //Reads in the user's weight and stores it in an array
printf("Now enter your height: ");
scanf("%f", &user_height[i]); //Reads in the user's height and stores it in an array.
}
printf("\n");
printf("USER BMI STATUS\n");
for ( i = 0; i < 10; i++ )
{
BMI = weight_value[i] / (user_height[i] * user_height[i]);
printf("%2d %23.7f \n", i+1 , BMI );
}
return 0;
}
I created an array of characters that holds the BMI Status strings, but since these are strings that are going to be deduced from expressions in the code, I have no idea how to print them on every line.
I thought of using if conditions to test for when the BMI values are true, but when I get to the part where I'm to add the argument that prints out the BMI Status string, I get confused.
If you really need every thing on one line you could write the mother of all tertiary operator expressions:
printf("%2d %23.7f %23s", i+1, BMI, BMI_Status[(BMI<18.5 ? 0 : (BMI < 24.9 ? 1 : (BMI < 29.9 ? 2 : 3)))])
In reality, this is just the if-elseif-else style from Joe M's answer rolled into a single line. Please note, I would never write something like this in production code, but rather
something the others have suggested.
To print the status according to the BMI calculated, you need to choose the proper index of the array holding the status value. You can achieve the same using a separate variable. Check the below code to get an idea.
#include <stdio.h>
#include <math.h>
int main(void) {
float weight_value[10];
float user_height[10];
float BMI = 0.0f;
char* BMI_Status[] = {"Underweight", "Normal", "Overweight", "Obese"};
int i;
int flag = -1; //used as index
for ( i = 0; i < 10; i++ )
{
printf("Please enter your weight: ");
scanf("%f", &weight_value[i]); //Reads in the user's weight and stores it in an array
printf("Now enter your height: ");
scanf("%f", &user_height[i]); //Reads in the user's height and stores it in an array.
}
printf("\n");
printf("USER BMI STATUS\n");
for ( i = 0; i < 10; i++ )
{
BMI = weight_value[i] / (user_height[i] * user_height[i]);
//after getting the BMI value, select the string index to be printed
if (BMI < 18.5)
{
flag = 0;
}
else if ((BMI > 18.5) && (BMI < 24.9 ))
{
flag = 1;
}
else if ((BMI > 24.9) && (BMI < 29.9 ))
{
flag = 2;
}
else if (BMI > 30)
{
flag = 3;
}
printf("%2d %23.7f \t\t%s\n", i+1 , BMI, BMI_Status[flag] ); //print the stats
}
return 0;
}
Note : You may want to add some checks to validate the data.