The following prompts input for the radius and height, and uses those values to calculate the volume of a cylinder. How can I write this program so that it doesn't terminate when the user inputs a negative value for either radius of height? The range has to be 1-10 inclusive and no other prompts are allowed. The loop must be terminated only when something non-numeric is entered.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
float areaCirc(float r){
return (M_PI*r*r);
}
float volCyl(float r, float h){
return (areaCirc(r)*h);
}
int main(void) {
float r, h;
int k = 0;
float volume;
float avgh = 0;
float toth = 0;
do{
float exit = scanf("%f%f", &r, &h);
if (exit == 0)
{break;}
if(r<=0 || r>10){
printf("Invalid radius: %.2f\n",r);
}
if(h<=0 || h>10){
printf("Invalid height: %.2f\n",h);
}
if(r>=0 && r<=10 && h>=0 && h <= 10){
volume = volCyl(r,h);
k = k++;
printf(" Cylinder %d radius %.2f height %.2f volume %.2f\n",k,r,h,volume);
toth = toth + h;
} }while(r>0 && h>0);
avgh = toth/k;
printf("Total Height: %.2f\n",toth);
printf("Average Height: %.2f\n",avgh);
return EXIT_SUCCESS;
}
Look at the statement inside your while(). Note that this will keep looping if and only if those conditions result in true.
do {
printf("Enter radius: ")
scanf("%d", &r);
printf("Enter height: ")
scanf("%d", &h);
} while(r<=0 || h<=0);
You can use a do-while loop that would keep prompting for the user to re-enter the radius and height is either value is less than or equals to 0.
Hope this helps :)
My specified range has to be 1 to 10 inclusive, without the negative values terminating the program, and no other prompts are allowed
Modify your main function
do{
int ex = scanf("%f%f", &r, &h); //scanf returns int
if (ex == 0)
{break;}
if(r<=0 || r>10){
printf("Invalid radius: %.2f\n",r);
continue;
}
if(h<=0 || h>10){
printf("Invalid height: %.2f\n",h);
continue;
}
// hence above conditions failed means you have given desired input
// need not to check any conditions
volume = volCyl(r,h);
k = k++;
printf(" Cylinder %d radius %.2f height %.2f volume %.2f\n",k,r,h,volume);
toth = toth + h;
}while(r>0 && h>0);
if(k>0) // check this other wise divide by zero will occur
{
avgh = toth/k;
printf("Total Height: %.2f\n",toth);
printf("Average Height: %.2f\n",avgh);
}
Related
Pls, help with the item 5 and 8 (the problem is described in the comment in code).
Here the task:
Using Euler's method to construct an approximate solution to the Cauchy problem with a given accuracy.
Write a program that calculates the approximate value of the solution to the Cauchy problem.
The initial condition (a and s (y(a)=s)) must be entered from the keyboard.
The point at which the approximate value (b) is calculated must be entered from the keyboard.
If inside or on the boundaries of the interval [a, b] the function has breakpoints (points that are not included in the Feasible region), a message should be displayed on the screen with a proposal to enter a new interval. Feasible region can be calculated manually for your specific option.
The permissible calculation error must be entered from the keyboard.
The first approximation should be calculated for n = 1. Then, when calculating each next iterative value, the number of segments should be increased in dividing the interval by 1.
It is worth stopping the iterative process if the modulus of the difference between the last two approximations is less than the specified error.
If n exceeds 10000, and the required accuracy is not achieved, display the current answer and the current error with the remark "It was not possible to achieve the specified accuracy."
The screen should display the last total value (final answer), rounded in accordance with the error, as well as the required number of iterations.
#include <math.h>
#include <stdio.h>
//round y
double round_y(double y, int count) {
return round(y * pow(10, count)) / pow(10, count);
}
//function
const double f(double x, double y){
return 2.0*x*sqrt(y)-y;
}
int main(){
int i, n;
double y, xi, yi, h, a, b, s, eps;
printf("Enter value a = ");
scanf("%lf",&a);
xi=a;
printf("Enter value b = ");
scanf("%lf",&b);
printf("Enter value s = ");
scanf("%lf",&s);
yi=s;
printf("Enter value eps = ");
scanf("%lf",&eps);
//Here the problem item 8
//There should be a function here for
//counting decimal places in error for further rounding
//but for example I just write by myself count
int count = 1;
//Euler's method
n=1; //Here the problem item 5 (iterations always is 1)
int iter_count = 0;
while(xi<n){
h=(b-a)/n;
y=yi+h*f(xi,yi);
iter_count=iter_count+1;
//printf("\ny = %lf\n", y);
if (fabs(y-yi)<eps){
printf("\nDifference modulus greater than error\n");
break;
}
//printf("\nyi = %lf\n", yi);
yi=y;
//printf("\nxi = %lf\n", xi);
xi=xi+h;
n++; //Here the problem item 5
if (n>10000.0){
printf("\nIt was not possible to achieve the specified accuracy\n");
break;
}
if (y==0.0){
printf("\nERROR Feasible region!\nPlease enter a new spacing\n");
break;
}
}
printf("___________________________________\n");
printf("The y value is %lf\n", round_y(y, count));
printf("Eps is %lf\n",eps);
printf("The number of iterations is %d\n",iter_count);
}
for item5 you need the function firstdecplace()
for item8 you need two loops
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
//round y
double round_y(double y, int count) {
return round(y * pow(10, count)) / pow(10, count);
}
//function
const double f(double x, double y){
return 2.0*x*sqrt(y)-y;
}
unsigned int firstdecplace( double error ) //item 5
{
if( error <= 0 )
{
printf( "Error at firstdecplace: argument smaller equals 0\n" );
exit(1);
}
unsigned int firstdec = 0;
while( error < 1 )
{
firstdec++;
error *= 10;
}
return firstdec;
}
int main(){
int i, n;
double y, xi, yi, h, a, b, s, eps;
printf("Enter value a = ");
scanf("%lf",&a);
xi=a;
printf("Enter value b = ");
scanf("%lf",&b);
printf("Enter value s = ");
scanf("%lf",&s);
yi=s;
printf("Enter value eps = ");
scanf("%lf",&eps);
int count = 1;
//Euler's method
int epsflag = 0;
double approx; // approximation of y(b)
int iter_count = 0;
for( n = 1; n < 10000; ++n ) // item 8 from here on
{
xi = a;
for( int iteration = 0; iteration < n; ++iteration )
{
h=(b-a)/n;
y=yi+h*f(xi,yi);
iter_count=iter_count+1;
if( fabs(y-yi) < eps ){
printf("\nDifference modulus smaller than error\n");
n--;
epsflag = 1;
break;
}
yi=y;
xi=xi+h;
}
if( epsflag == 1)
{
break;
}
approx = y;
if (y <= 0.0){
printf("\nERROR Feasible region!\nPlease enter a new spacing\n");
break;
}
}
if(n == 10000){
printf("\nIt was not possible to achieve the specified accuracy\n");
}
printf("___________________________________\n");
printf("The y value is %lf\n", round_y(approx, firstdecplace(eps)));
printf("Eps is %lf\n",eps);
printf( "number of iteration for the approxmation of y(b): %d\n", n );
printf("The number of total iterations: %d\n",iter_count);
}
I'm fairly beginning in C, and was working on an assignment that asks me to take user inputs between -50 and 100 and then calculate various characteristics of the numbers entered such as average, even/odd, etc. (the program will stop once -999 is entered). I am also supposed to have the program Pause and display the output, and once the user presses any key, the screen will clear and another number will be entered by the user.
Everything else is functioning properly, and the code so far looks like:
#include <stdio.h>
#include <ctype.h>
int main()
{
//used for math
int i = 0;
float num[100], sum = 0.0, average;
//user input number
float x = 0.0;
//used to determine minimum and maximum numbers
unsigned int min, max, buf;
//used for determining prime number
int flag;
//for pause button
char ch;
while (1) {
printf("%d. Enter number: ", i + 1);
scanf("%f", &x);
//establish exit number
if (x == -999)
break;
//make sure number is within range
if (x >= -50 && x <= 100)
{
num[i] = x;
sum += num[i];
i++;
//determin minimum and maximum
if (x >= buf)
{
max = x;
}
if (x <= buf)
{
min = x;
}
buf = x;
}
else
{
printf("invalid number, must enter between -50 and 100\n");
}
}
average = sum / i;
//determine if prime num
if (x / i == 0)
{
flag = 1;
}
//display output
printf("\n Average = %.2f", average);
printf("\n Sum = %.2lf", sum);
printf("\n Numbers entered = %d", i);
printf("\n The highest value entered : %u", max);
printf("\n The lowest value entered : %u", min);
if (x / 2 == 0)
printf("\n%.2f is even.", x);
else
printf("\n%.2f is odd.", x);
//determine prime number
if (flag == 0)
{
printf("\n%.2f is a prime number.", x);
}
if (flag == 1)
{
printf("\n%.2f is not a prime number.", x);
}
printf("\nThank you for using my program, have a nice day :)");
return 0;
}
The pause button is the only thing that is not functioning properly. Would there be anyone that would know the answer of the best way to achieve the described pause button function? Thanks :)
Edit: I don't have the same problem as the "How to Pause in C" question, as I can see the output once -999 is entered, I just need to see the output one the screen is paused.
You can use getchar(); to pause your system. Once the user presses any key it will keep going. For clearing the screen you will need the #include<conio.h> library so that you can use the clrscr();
Here is a function for you to use:
#include<stdio.h>
#include<conio.h>
void func() {
getchar(); // Pauses the system until user presses a key
clrscr(); // Clears the screen
}
You can just call the function for every time you want it to pause and clear the screen. Since getchar(); will pause the system, it won't pass to the clrscr(); unless the user presses a key.
#include <stdio.h>
int printMenu(int);
int studentglobal;
float getCarryMark(float);
float cm1;
main()
{
printf("-----------------------------------------------------\n");
printf("\t\tTotal Score calculator\n");
printf("-----------------------------------------------------\n");
int counter, x, studentcount = 1,sum = 0 ;
x = printMenu(studentglobal);
for (counter = 0; counter < x; counter++)
{
studentcount = studentcount + counter;
printf("Student : %d \n", studentcount);
getCarryMark(cm1);
if (cm1 >= 0 && cm1 <= 50)
{
printf("right range!!\n");
}
else
{
printf("INVALID RANGE!!!\n");
}
printf("%.2f\n", cm1);
}
}
int printMenu(int nstudent)
{
printf("Enter no of student: ");
scanf("%d", &nstudent);
return(nstudent);
}
float getCarryMark(float carrymark)
{
printf("Enter your carrymarks: ");
scanf("%f", &carrymark);
return(carrymark);
}
So actually when I enter 200, it shows INVALID RANGE!!!, but when I enter 20 it still shows INVALID RANGE!!!. It somehow skipped the if statement. Please don't bother the other part, if I have any mistake tell me please. ert gf dfg dgd dg dfgd gd dg dg dgdfg
You need to return carrymark from getCarryMark:
float getCarryMark(float carrymark)
{
printf("Enter your carrymarks: ");
scanf("%f", &carrymark);
return(carrymark);
}
You are missing a return statement in getCarryMarks method !
You missed the return statement in getCarryMark
getCarryMark function takes a parameter by value, modifies the value and returns it back, however, the returned value is never used. Modifying the parameter's value does not reflect this change to the outside since it has been passed by value.
I have partially updated the code so that it could execute the if statement. Please try the following code.
#include <stdio.h>
int printMenu(int);
int studentglobal;
float getCarryMark(float);
float cm1;
main()
{
printf("-----------------------------------------------------\n");
printf("\t\tTotal Score calculator\n");
printf("-----------------------------------------------------\n");
int counter, x, studentcount = 1,sum = 0 ;
x = printMenu(studentglobal);
for (counter = 0; counter < x; counter++)
{
studentcount = studentcount + counter;
printf("Student : %d \n", studentcount);
cm1 = getCarryMark();
if (cm1 >= 0 && cm1 <= 50)
{
printf("right range!!\n");
}
else
{
printf("INVALID RANGE!!!\n");
}
printf("%.2f\n", cm1);
}
}
int printMenu(int nstudent)
{
printf("Enter no of student: ");
scanf("%d", &nstudent);
return(nstudent);
}
float getCarryMark()
{
float carrymark = 0.0;
printf("Enter your carrymarks: ");
scanf("%f", &carrymark);
return(carrymark);
}
I am confused on how to complete this for loop. The mission is to read input in unix. For the input if the radius is >0 it should prompt the user each time and then if <=0 it should terminate. I am going from centimeters to square inches. My current configuration requires 2 inputs (1 prompted, 1 not) before giving output to the console. Cheers.
#include <stdio.h>
#define PI 3.14159
main()
{
float r, a;
int y = 9999999;
for(int i =0; i <y; i++){
printf("Enter the circle's radius (in centimeters): ");
scanf ("%f", &r);
if(r>0){
r=r;
a = PI * r * r *2.54;
printf("Its area is %3.2f square inches.\n", a);
} else {}
}
}
Your code flow is the following:
for (infinite condition) {
scan input
if (input > 0) {
do things
}
else {
do nothing
}
}
So there's no way to exit out of the loop, that's why the break statement exists, to force quitting an iterative block of code:
while (true) {
scanf ("%f", &r);
if (r > 0) {
// do whatever;
}
else
break;
}
The break will stop the cycle when executed, just going out of the loop.
You may want to try using a while loop instead so that the question is continually prompted until the user inputs a value =>0. see if below helps (also your conversion factor was not quite right);
#include <stdio.h>
#define PI 3.14159
void main()
{
float r, a;
printf("Enter the cirle's radius (in centimeters):");
scanf("%f",&r);
while (r>0)
{
a=PI*r*r*0.155; // conversion from sqcm to sqin is ~0.155
printf("Its area is %3.2f square inches \n", a);
printf("Enter the cirle's radius (in centimeters):");
scanf("%f",&r);
}
}
r=1.0f;
// break if no. of cases exhausted or r is negative or zero
for(int i =0; i < y && r > 0; i++)
{
printf("Enter the circle's radius (in centimeters): ");
if( scanf ("%f", &r) == 1) // Always check for successful scanf
{
a = PI * r * r/2.54/2.54; //This is correct formula
printf("Its area is %3.2f square inches.\n", a);
}
}
Consider a while loop instead:
#include <stdio.h>
#define PI 3.14159
main(){
float r, a;
int continueBool = 1;
while(continueBool == 1){
printf("Enter the circle's radius (in centimeters): ");
scanf ("%f", &r);
if(r>0){
a = PI * r * r *2.54;
//the above formula may be wrong, so consider trying:
//a = PI * r * r/2.54/2.54;
printf("Its area is %3.2f square inches.\n", a);
}
else{
continueBool = 0;
}
}
}
The break statement can be dangerous if you are new to C programming, so I recommend not using it until you get a better understanding of C and break. If you do want to use break, then this could be your solution:
#include <stdio.h>
#define PI 3.14159
main(){
float r, a;
while(1){
printf("Enter the circle's radius (in centimeters): ");
scanf ("%f", &r);
if(r<=0){
break;
}
a = PI * r * r *2.54;
//the above formula may be wrong, so consider trying:
//a = PI * r * r/2.54/2.54;
printf("Its area is %3.2f square inches.\n", a);
}
}
Use this:
for(int i =0; i < y; i++)
{
printf("Enter the circle's radius (in centimeters): ");
scanf ("%f", &r);
if(r > 0)
{
a = PI * r * r *2.54;
printf("Its area is %3.2f square inches.\n", a);
}
else
{
break;
}
}
I am working on an assignment in C where I have to read in multiple people's heights and weights and determine their bmi. I then classify them into their respective bmi categories, but I am getting stuck on how to do this properly, this is my code thus far:
# include <stdio.h>
int main () {
int people;
double bmi, weight, inches;
printf("How many peoples? > ");
scanf("%d", &people);
do {
printf("Enter height (inches) and weight (lbs) (%d left) > ", people);
scanf("%lf %lf", &inches, &weight);
people--;
}
while (people > 0);
bmi = (weight / (inches * inches)) * 703;
if (bmi < 18.5) {
printf("Under weight: %d\n", people);
}
else if (bmi >= 18.5 && bmi < 25) {
printf("Normal weight: %d\n", people);
}
else if (bmi >= 25 && bmi < 30) {
printf("Over weight: %d\n", people);
}
else if (bmi >= 30) {
printf("Obese: %d\n", people);
}
return 0;
}
where am i going wrong? where do i fix this code?
Use some data structure for storing data. You are getting input for more than one people but, finally processed for one person.
And also people--; is done. so people variable is decremented up to zero, which makes while to exit without executing your BMI calculation.
Modified Code:
#include <stdio.h>
#define MAX_PEOPLE 100
int main () {
int people;
double bmi[MAX_PEOPLE], weight[MAX_PEOPLE], inches[MAX_PEOPLE];
int index = 0;
printf("How many peoples? > ");
scanf("%d", &people);
index = people;
do {
printf("Enter height (inches) and weight (lbs) (%d left) > ", index);
scanf("%lf %lf", &inches[index], &weight[index]);
index--;
}while (index > 0);
for(index = 0; index < people; index++)
{
bmi[index] = (weight[index] / (inches[index] * inches[index])) * 703;
if (bmi[index] < 18.5) {
printf("Under weight: %d\n", index);
}
else if (bmi[index] >= 18.5 && bmi[index] < 25) {
printf("Normal weight: %d\n", index);
}
else if (bmi[index] >= 25 && bmi[index] < 30) {
printf("Over weight: %d\n", index);
}
else if (bmi[index] >= 30) {
printf("Obese: %d\n", index);
}
}
return 0;
}
Right now you are processing the same data.
Each time you assign a new value to weight the old one is erased.
You could create multiple variables like so:
double weight1, weight2, weight3, weight4, ...etc (highly unpractical!!)
or
create an array of doubles:
double weight[100];
and refer to each specific double variable like this:
scanf("%lf %lf", inches[0], weight[0]);
scanf("%lf %lf", inches[1], weight[1]);
scanf("%lf %lf", inches[2], weight[2]);
You see where i-m getting at ? you can manipulate the array tru a for loop.