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;
}
}
Related
I'm in an introductory code class for C and I'm trying to run this square and cube calculation if a number greater than 1 is entered, but it stalls if I run it. I'm not getting any errors and I've tried different ways to make this work through tips here, but nothing is happening and I don't know enough to get what's wrong.
#include <stdio.h>
int main ()
{
int num, square, cube;
printf("What is your number? ");
scanf("%d", num);
if (num > 1)
{
square = num * num;
cube = num * num * num;
printf("\nThe square of your number is ");
printf("%d", &square);
printf(" and the cube of your number is ");
printf("%d", cube);
printf(".");
}
printf("\nPlease enter a number greater than 1.");
return 0;
}
Add & in scanf, remove & while printing. The & operator evaluates to the memory location of the variable. In scanf we are supposed to use &, so that the input is stored in the memory address obtained by writing &var.
Exit the program after printing the square and cube, or place the next printf in an else block.
#include <stdio.h>
int main ()
{
int num, square, cube;
printf("What is your number? ");
scanf("%d", &num);
if (num > 1)
{
square = num * num;
cube = num * num * num;
printf("\nThe square of your number is ");
printf("%d", square);
printf(" and the cube of your number is ");
printf("%d", cube);
printf(".");
return 0;
}
printf("\nPlease enter a number greater than 1.");
return 0;
}
#include <stdio.h>
int main ()
{
int num, square, cube;
printf("What is your number? ");
scanf("%d", &num);
if (num > 1)
{
square = num * num;
cube = num * num * num;
printf("\nThe square of your number is ");
printf("%d", square);
printf(" and the cube of your number is ");
printf("%d", cube);
printf(".");
}
else
printf("\nPlease enter a number greater than 1.");
return 0;
}
printf("%d", num); you made mistake use printf("%d", num); when you use Address operator & in print statement it will print address not value so
printf("%d", square); // remove & sign
Also put last print statement under else otherwise it will run everytime
Why we should use ampersand (&) in scanf. The ampersand (&) allows us to pass the address of variable number which is the place in memory where we store the information that scanf read.
You are experiencing a common error called "Segmentation fault" which occurs when you access a memory location which is not allowed.
As others have pointed out, use & operator in scanf while reading the num variable.
you don't have to use & in printf
#include <stdio.h>
int main ()
{
int num, square, cube;
printf("What is your number? ");
scanf("%d", num);
if (num > 1)
{
square = num * num;
cube = num * num * num;
printf("\nThe square of your number is ");
printf("%d", square);
printf(" and the cube of your number is ");
printf("%d", cube);
printf(".");
}
printf("\nPlease enter a number greater than 1.");
return 0;
}
This is the code for finding the numerical solutions of 1D Heat Transfer Equation(well, possibly). The code is getting compiled but the console is not showing any output. The console is staying and not disappearing either. I have tried with getch() and getchar() also but the problem still persists. Please help!
Here's my code:
#include <stdio.h>
#include <math.h>
int
main (int argc, const char *argv[])
{
int a, p, tmax, tmin, l;
int i, j, n, o;
double m, T1, T2, x, al, H[l + 1][tmax + 1];
float k;
printf ("Enter the number of nodes: \n");
scanf ("%d", &a);
printf ("Enter the thickness of the wall: \n");
scanf ("%d", &l);
printf ("Enter the value of maximum time coordinate: \n");
scanf ("%d", &tmax);
printf ("Enter the value of minimum time coordinate: \n");
scanf ("%d", &tmin);
printf ("Enter the number of time steps: \n");
scanf ("%d", &p);
printf ("Enter the value of thermal diffusivity: \n");
scanf ("%f", &k);
printf ("Enter the value of initial temperature: \n");
scanf ("%lf", &T1);
printf ("Enter the values of temperature at both the boundaries: \n");
scanf ("%lf", &T2);
x = (l / (a - 1)); /*change in spacial coordinate*>
m = (tmax - tmin) / (p - 1); /*change in time coordinate*/
al = (k * (m)) / (pow (x, 2)); /*Formula for CFL constant*/
printf (" The vale of the constant is %lf\n", al);
printf ("the value of the constant should be less than 0.5 for the convergence of iterative
formula. \n");
for (o = 0; o <= tmax; o++)
{
H[0][o] = H[l][o] = T2; /*boundary condition*/
}
for (j = 1; j <= (l - 1); j++)
{
H[j][0] = T1; /*initial condition*/
}
if (al <= 0.5)
{
for (n = 0; n <= (tmax - 1); n++)
{
for (i = 1; i <= (l - 1); i++)
{
H[i][n + 1] =
H[i][n] + (al * (H[i + 1][n] - (2 * H[i][n]) + H[i - 1][n])); /* Iterative Formula for finding the temperature at each grid point*/
printf (" The value of Temperature[i,n] at [i,n] is:\n ");
printf ("%lf at %d , %d is", H[i][n], i, n);
printf ("\n");
}
}
}
else
{
printf ("Error! Solution is unstable. \n");
}
return 0;
}
What's wrong with my code?
Also, how can I take a mathematical function as input from the user instead of T2 in the place of the initial temperature? Sometimes, 1D unsteady heat transfer problems has initial temperature in the form of a mathematical function which can be algebric, trigonometric, hyperbolic etc. like in this problem
"Show that the solution of the ∂2θ/∂x2= ∂θ/∂t
satisfying the conditions (i) θ → 0 as t → ∞, (ii) θ = 0
when x = ±a for all values of t > 0, and (iii) θ = x when t = 0 and −a < x < a is
θ(x,t) = 2a/π ∑(n=1) to ∞((-1)^(n-1))(1/n)(sin(nπx/a) * (exp^((-((nπ)^2)* t)/a^2 )))"
So, I need to take a mathematical function as input from the user. Is there any way to do that using the C standard library? I found a way to do it using expression evaluator/parser but is there any other simpler way to solve this problem?
I am new to the C programming language. I am attempting to run the code below an N amount of times (based on the user input of "Enter amount of iterations"). I am trying to do this using a for loop (also tried with a while loop) but have been unsuccessful.
Whenever I run the code below, my terminal continuously repeats "Enter two float numbers:". I have to close the terminal and reopen it to try again. Does the issue have to do with my for loop? I am interpreting my for loop as: "a=0; if a > 0; increment a". Is there a way I can set a limit for "if a > 0" or should I be using a while loop? If the user enters "3" for amount of iterations, I am expecting the program to ask "Enter two float numbers" 3 times (with the answer).
float sum (float m, float n){
return m+n;}
int main() {
float x, y;
int a;
printf("Enter amount of iterations: ");
scanf("%d", &a);
for (int i; i < 0; i++) {
printf("Enter two float numbers: ");
scanf("%f %f", &x, &y);
float su = sum(x,y);
printf("%f and %f = ", x, y);
printf("%f\n", su);}
return 0;}
CORRECT ANSWER Formatted for readability:
float sum(float m, float n)
{
return m + n;
}
int main()
{
float x, y;
int a;
printf("Enter amount of iterations: ");
scanf("%d", &a);
for (int i = 0; i < a; i++)
{
printf("Enter two float numbers: ");
scanf("%f %f", &x, &y);
float su = sum(x, y);
printf("%f and %f = ", x, y);
printf("%f\n", su);
}
return 0;
}
This should behave more like you would like it to:
#include <stdio.h>
static float sum(float m, float n)
{
return m + n;
}
int main(void)
{
float x, y;
int a;
printf("Enter amount of iterations: ");
if (scanf("%d", &a) != 1)
{
fprintf(stderr, "Invalid input for iterations\n");
return 1;
}
for (int i = 0; i < a; i++)
{
printf("Enter two float numbers: ");
if (scanf("%f %f", &x, &y) != 2)
{
fprintf(stderr, "Failed to read to floating point numbers\n");
return 1;
}
float su = sum(x, y);
printf("%f and %f = ", x, y);
printf("%f\n", su);
}
return 0;
}
Note that it checks that the input operations are successful, and reports errors on standard error (stderr). The code uses a standard C for loop to count from 0 up to a limit — this is idiomatic C. You should get used to using it.
As I noted in a comment, the a in the for loop is different from and unrelated to the a declared earlier in your code and set by the input operation. The a in the for loop is not initialized; you can't tell how many times the loop will be executed. A good compiler should warn you about redefining or shadowing a.
for (i = 0; i < a; i++); - answer provided by J.S!
After compiling, my GetInt function causes the printf statements within the function to be printed on the screen three times. I believe this was caused when I initialized all radius, base, and height to GetInt(void) but I see no other way of accurately initializing those variables. Please help!
#define _CRT_SECURE_NO_WARNINGS
#define PI 3.14159
#include <stdio.h>
#include <math.h>
int GetInt(void);
double CalcTriangleArea(int base, int height);
double CalcCircleArea(int radius);
int main(void)
{
int radius, base, height;
double triangleArea;
double circleArea;
radius = GetInt();
base = GetInt();
height = GetInt();
triangleArea = CalcTriangleArea(base, height);
circleArea = CalcCircleArea(radius);
return(0);
}
int GetInt(void)
{
int x;
{
printf("Please enter a radius: \n\n");
scanf("%d", &x);
printf("Please enter a base: \n\n");
scanf("%d", &x);
printf("Please enter a height: \n\n");
scanf("%d", &x);
}
return(x);
}
double CalcTriangleArea(int base, int height)
{
double triangleArea;
printf("Triangle area is %.2f \n\n", triangleArea = .5*base*height);
return(0);
}
double CalcCircleArea(int radius)
{
double circleArea;
printf("Area is %.4f \n\n", radius, circleArea = PI * pow(radius, 2));
return(0);
}
A rule of thumb is to avoid repeating yourself whereever possible and don't repeat yourself. Imagine you want to change from two new lines (\n\n) to three (\n\n\n)? You would need to make that change three times.
Looking at the bare bones of GetInt, you are printing a prompt, two new lines, get a value and returning it. Thus, we can write the new function like this:
void getInt(char* prompt)
{
int x, numberOfConversions; // numConversions is the number of int's read from the keyboard buffer
printf("%s: \n\n", prompt);
numberOfConversions = scanf("%d", &x);
while (numberOfConversions != 1) // while the user did not enter a number
{
printf("Please enter a number: ");
numberOfConversions = scanf("%d", &x)"
}
return x; // Always returns a valid number
}
GetInt asks for, and reads, 3 distinct values, yet returns only the last one, every time it is called.
I think what you really want is to have GetInt ask for and return just 1 value, either passing it the prompt to print or printing it before calling it.
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);
}