C program is not showing output even though it is getting compiled - arrays

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?

Related

Print biggest and smallest numbers ,until -1 is given [duplicate]

This question already has answers here:
Min and max in C using basics
(4 answers)
Closed 4 years ago.
It works, but if you don't enter any number smaller than 0 it doesn't print the smaller value and prints 0.
int max = 0;
int min = 0;
int a;
printf("Enter a number:\n");
scanf("%d", &a);
while (a != -1){
if (a < min){
min = a;
}
if (a > max){
max = a;
}
scanf("%d", &a);
}
printf("Your largest number is %d. Your smallest number is %d.", max, min);
It's because your initial min is zero so no positive value is going to be less than that.
You're better off changing your loop construct so that initial value is loaded no matter what, something like:
int a, min = 0, max = 0, first = 1; // Force first number to be used.
printf ("Enter a number:\n");
scanf ("%d", &a);
while (a != -1) {
if (first || a < min) min = a;
if (first || a > max) max = a;
first = 0; // Reset after first number.
scanf ("%d", &a);
}
printf ("Largest is %d, smallest is %d.\n", max, min);
You should probably also check the return value from scanf so as to catch non-integer input. That's a way to have more robust code but, for educational programs, it's probably okay (at least as long as you understand the implications).
This could be as simple as replacing:
scanf ("%d", &a)
with something like:
if (scanf ("%d", &a) != 1) {
puts ("Invalid input.");
exit(1);
}

My code is not running in Xcode, scanner issue

#include <stdio.h>
#include <math.h>
#define M_PI 3.14
int main(void)
{
// Declaring Variables
float time, p1, p2, p3, voltage, p3_num, p3_dem, epsilon;
int index, type;
// Asking user for time and index values into equation
printf("Please enter a time value: ");
scanf("%f", &time);
printf("Please enter an index value: ");
scanf("%d", &index);
// Calculate value for given time, part a, b, or c
printf("Do you want to run type a, b, or c?: ");
scanf("%d", &type);
char again = 'Y';
while (again == 'Y')
{
if (type == 'a') {
int going = 'Y';
while (going == 'Y')
{
// Different parts of formula to ensure accuracy
printf("Please enter an index value: ");
scanf("%d", &index);
p1 = ((3 / 2) - 12 / pow((M_PI), 2));
p2 = (1 / pow((double)(2 * index - 1), 2));
p3_num = ((2 * index - 1) * M_PI * time);
p3_dem = 3;
p3 = cos(p3_num / p3_dem);
voltage = p1 * p2 * p3;
printf("time = %f", time);
printf("index = %i", index);
printf("voltage = %f", voltage);
printf("Again? (Y/N)");
scanf("%c", &going);
}
}
}
}
There is more underneath, but this is the main bulk. What I am confused about is that none of this running, none. I start at the very beginning and comment out everything else, not even my print statement is running. What is wrong?
You should divide your program up into smaller function so you can test them individually.
For example here would be a function that reads in one integer.
int GetInteger(const char * msg)
{
//read up on c style formatting here is a source http://en.cppreference.com/w/c/io/fscanf
int i = 0;
printf("%s", msg);
scanf("%i", &i);
printf("Program confirms: %i\n", i);
return i;
}
This will help you down the road. Read up on SOLID principles and Test Driven Development.

How to read number input of unsure length?

I've been stuck on a problem for awhile, I need to read input from the user in the form,
5 1.2 2.3 3.4 4.5 5.6
where the first integer is the number of floats to expect, and then the floats following are the values I need to store in an array of that size. The code I have that keeps returning an error is,
...
int i = 0, j, k;
float value, *ptr;
// For every element in inputArr...
while (i < inputLength) {
printf("Enter the number of values in this data set, followed by the values: ");
// Get the int value for array creation...
scanf("%d ", &j);
printf("%d", j);
// Save it for the calculations later.
*(lengths + i) = j;
// Create dynamic array of floats.
*(inputArr + i) = calloc(j, sizeof(float));
ptr = *(inputArr + i);
// For the rest of the input read the floats and place them.
k = 0;
while (k < j-1) {
scanf("%f ", &value);
*(ptr + k) = value;
k++;
}
scanf("%f\n", &value);
*(ptr + j - 1) = value;
i++;
}
This throws a segmentation fault when I enter in the input above.
Can someone help me out by telling me what I'm doing incorrectly?
You do not have to include spaces and end-of-strings in your scanf calls.
scanf("%d", &j);
i/o
scanf("%d ", &j);
scanf("%f", &value);
i/o
scanf("%f\n", &value);
etc.

For Loop in C- implementation

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;
}
}

Printf Problem with While Loop

I'm creating a temperature converter in C. Basically, you input a minimum and maximum value in degrees Celsius, along with a step, and it displays that information in a list, along with the Fahrenheit equivalent. On some occasions, I have noticed the last Fahrenheit entry not being displayed when it should. For example, when you input a lower limit of 10, a higher limit of 30, and a step of 4, it cuts off the last Fahrenheit temperature. I know it's something to do with the last while loop, but I just can't figure it out.
#include <stdio.h>
int main (int argc, const char * argv[]) {
double l, h, s;
double lf, hf, sf;
/* Number rows in tables */
int num1, num2;
num1 = 1;
num2 = 1;
/* Lower limit input */
printf("Please give a lower limit: ");
scanf("%4lf", &l);
while (l < 0) {
printf("Lower limit must be greater than 0: ");
scanf("%4lf", &l);
}
/* Stores value for Fahrenheit conversion */
lf = l;
/* Higher limit input */
printf("Please give a higher limit: ");
scanf("%4lf", &h);
while (h <= l) {
printf("Higher limit must be greater than lower limit: ");
scanf("%4lf", &h);
}
while (h >= 50000) {
printf("Higher limit must be less than 50000: ");
scanf("%4lf", &h);
}
hf = h;
/* Step input */
printf("Please input step: ");
scanf("%4lf", &s);
while (s <= 0) {
printf("Step must be greater than 0: ");
scanf("%4lf", &s);
}
while (s >= h - l) {
printf("Step must be less than the difference in temperatures: ");
scanf("%4lf", &s);
}
sf = s;
/* Celsius table */
printf("\nCelsius\n-------\n");
while (l <= h) {
printf("%i. %4lf\n", num1, l);
num1++;
l = l + s;
}
/* Fahrenheit table */
printf("\nFahrenheit\n----------\n");
/* Converts Celsius to Fahrenheit */
lf = (lf * 1.8) + 32;
hf = (hf * 1.8) + 32;
sf = sf * 1.8;
printf("Lower input: %4lf\n", lf);
printf("Higher input: %4lf\n", hf);
printf("Step: %4lf\n----------\n", sf);
/* This while loop sometimes cuts off the last entry */
while (lf <= hf) {
printf("%i. %4lf\n", num2, lf);
num2++;
lf = lf + sf;
}
return 0;
}
The problem is with comparing the doubles, you might get into a situation where something like 10 + 1.8 evaluates to 11.800000001 and thus missing the end value.
The solution to your problem would be to first calculate the number of steps:
int steps = (h - l) / s + 1; //Might want to apply rounding
And then use a for/while loop over the integer variable instead:
for (int i = 0; i < steps; ++i) {
double t = l + (h - l) * i / (steps - 1);
}
for (int i = 0; i < steps; ++i) {
double tf = lf + (hf - lf) * i / (steps - 1);
}
while (lf <= hf)
You are comparing Double values, You will face problems of Precison & Rounding Errors, Most likely that causes the last iteration to not execute at all.
This answer of mine, should be a good read.
Choose a precision and compare it with the difference between hf and lf(abs value).
Also keep in mind with a random fixed step you will not always reach the top value of the interval. it might work if step divides h-l but it won't work otherwise.
Directly after your last while loop, add the following code (and don't forget to #include assert.h):
printf("lf = %f, hf = %f\n", lf, hf);
assert(lf == hf);
you should get this output:
Celsius
-------
1. 10.000000
2. 14.000000
3. 18.000000
4. 22.000000
5. 26.000000
6. 30.000000
Fahrenheit
----------
Lower input: 50.000000
Higher input: 86.000000
Step: 7.200000
----------
1. 50.000000
2. 57.200000
3. 64.400000
4. 71.600000
5. 78.800000
lf = 86.000000, hf = 86.000000
Assertion failed: lf == hf, file randomdudescode.c, line 77
Which is incredibly confusing, because obviously lf == hf.
This illustrates one of the quirks of C and floating point tomfoolery in general. You have to deal with rounding errors and imprecision.

Resources