Get evenly spaced numbers in a range, in C - c

I am trying to perform an easy calculation without beeing able to figure out the right approach to it: I am trying to obtain a specific amount of N values, reading the step number from user input, within a certain range included between min and max also read from the user input. Those N values must be evenly spaced between themselves.
For instance, this should be able to produce a set of N numbers including the lower range limit and the upper one. I need to use decimal min and max and integer number of step.
This is the code I am trying to use:
#include <stdio.h>
int main()
{
double min;
double max;
int step;
double table_array[step];
table_array[0] = min;
printf("Enter the minimum value: ");
scanf("%lf", &min );
printf("Enter the maximum value: ");
scanf("%lf", &max );
printf("Enter the evenly spaced step value: ");
scanf("%d", &step );
printf("\n----------------------------------\n");
int i;
int increment;
for (i = 0; i <= step; i++){
increment = (max - min) / step;
table_array[i+1] = table_array[i] + increment;
while (table_array[i] < max){
printf("%i %lf\n",i, table_array[i]);
}
}
return 0;
}
I need to improve the for cycle for sure. Any suggestions? I assume it can be even totally wrong since it is not running, or better yet it is running but not showing the right result

First of all, you need declare an array with specific size. Initially the array size is not valid as step will initially have garbage value. then you are trying to print i with %i need to change that one with %d. with your step you need to calculate the increment only once. and as your increment can be double number then just make sure that you are using a double type for increment. now how i calculate the increment as 2 number must be min and max then there must be step >= 2 . suppose max =20 min =10 and step=3 so the numbers will be 10,15,20. so increment = (max -min )/(step-1) = 5. now make some complex case . if step = 1 then min must be equal to max. we need to check this case explicitly. another case if max < min then just need to swap them.
here is the code:
#include <stdio.h>
int
main ()
{
double min;
double max;
int step;
printf ("Enter the minimum value: ");
scanf ("%lf", &min);
printf ("Enter the maximum value: ");
scanf ("%lf", &max);
printf ("Enter the evenly spaced step value: ");
scanf ("%d", &step);
double table_array[step + 5];
table_array[0] = min;
printf ("\n----------------------------------\n");
int i;
double increment;
if (max < min){
double temp;
temp = min;
min = max;
max = temp;
}
if (step == 1 && max == min) {
i = 0;
printf ("%d %.18lf\n", i, table_array[i]);
} else {
increment = (max - min) / (step - 1);
i = 0;
printf ("%d %.18lf\n", i, table_array[i]);
for (i = 1; i < step; i++){
table_array[i] = table_array[i - 1] + increment;
printf ("%d %.18lf\n", i, table_array[i]);
}
}
return 0;
}

#include <stdio.h>
#define SWAPI(min,max,type) do{type tmp; if(min > max) {tmp = max; max = min; min = tmp;}}while(0)
double *getnumbers(double *table, size_t nelements, double max, double min)
{
double step;
if(table && nelements > 1 )
{
SWAPI(min,max, double);
step = (max - min) / (nelements - 1);
for(size_t element = 0; element < nelements; element++, min += step)
{
table[element] = min;
}
}
else
{
table = NULL;
}
return table;
}
void printtable(double *table, size_t num)
{
for(size_t i = 0; i < num; i++)
{
printf("[%zu] = %f\n", i, table[i]);
}
}
int main(int argc, char* argv[])
{
double numbers[25];
if(getnumbers(numbers,2,3,6)) printtable(numbers, 2);
printf("\n");
if(getnumbers(numbers,15,3,6)) printtable(numbers, 15);
}
https://godbolt.org/z/odscs6

#include <stdio.h> // printf, scanf, putchar
#include <float.h> // FLT_EPSILON
#include <math.h> // fabs
int isequal(double, double);
int main(void) {
double min, max, step, nnum;
printf("Maximum: "), scanf("%lf", &max); // Get maximum
printf("Minimum: "), scanf("%lf", &min); // Get minimum
if (min > max) { // If invalid maximum, handle error
puts("Maximum cannot be over minimum");
return 1; // Returning 1 indicates program failure
}
printf("Step: "), scanf("%lf", &step); // Get step
nnum = (max - min)/step;
if (!isequal(nnum, (int) nnum) || step <= 0) { // If invalid step, handle error
puts("Invalid step");
return 1;
}
putchar('\n'); // Separate input from output
for (int i = 0; i <= nnum; i++) {
printf("%d. %lf\n", i + 1, min);
min += step; // We already know it will go into maximum evenly
}
return 0; // Returning 0 indicates program success
}
int isequal(double x, double y) { // fabs() = Float absolute value
return fabs(x - y) < FLT_EPSILON; // FLT_EPSILON = Smallest comparable float value
}

Related

How to find max&min in while loop - c

I know that this is very easy question for you, but for me as beginner very hard. To get to thing. I have to create program that will take as many numbers as I want and then write max and min from them. Numbers can have decimals so that´s why double. Everything goes great as far as I trouble-shot until while cycle begins. I always get 0 on output on both min and max values. Anyone knows why?
Code:
main() {
int a = 0, b = 0, min = 1000, max = 0;
printf("How many numbers do you want to enter\n");
scanf("%d", & a);
b = a;
double n[b];
printf("Write those numbers\n");
for (b = 0; a > b; b++) {
scanf("%lf", & n[b]);
}
b = 0;
while (1) {
if (n[b] < n[b + 1])
max = n[b + 1];
if (min > n[b])
n[b] = min;
b++;
if (b == a)
break;
}
printf("Minimum: %lf\nMaximum: %lf", min, max);
}
There are multiple problems:
You defined min as 1000, what if all numbers entered will be bigger than that?
min and max should be doubles too
By using n[b + 1] when b == a you're going after array bounds
The most optimal way to solve this is to calculate min/max in one loop, like this:
main() {
int i, len;
double tmp, min = NAN, max = NAN; // its better to initialize values to NAN to cover case when len is 0
printf("How many numbers do you want to enter\n");
scanf("%d", & len);
for (i = 0; i < len; ++i) {
scanf("%lf", & tmp);
if ((i == 0) || (tmp < min)) min = tmp;
if ((i == 0) || (tmp > max)) max = tmp;
}
printf("Minimum: %lf\nMaximum: %lf\n", min, max);
}
Printing an int using a conversion specifier for double is not a good idea, but invokes the infamous Undefined Behaviour.
The compiler might have noticed you about this. If it didn't, then increase its warning level. For GCC use -Wall -Wextra -pedantic.
So to fix this either make min and max be double
int a = 0, b = 0;
double min = 1000., max = 0.; /* Such initialisations limit your input. */
or leave them be int (decreasing accuracy), and print them as what there are, namely int
printf("Minimum: %d\nMaximum: %d\n", min, max);
I know I'm late but I think this is the best way to do this program
#include <stdio.h>
int main() {
int a = 0;
int counter = 0;
double min;
double max;
int counter = 1;
printf("How many numbers do you want to enter\n");
scanf("%d", & a);
double val;
printf("Write those numbers\n");
scanf("%lf", & val);
min = val;
max = val;
while(counter < a)
{
scanf("%lf", & val);
if(val < min)
{
min = val;
}
if(val > max)
{
max = val;
}
counter++;
}
printf("Minimum: %lf\nMaximum: %lf\n", min, max);
return 0;
}
this will read in values continuously by first setting the min and max values to whatever the first value is.I'm a c++ programmer not a c programmer but this seems like a better idea.

Calculating Arithmetic and Geometric mean by introducing numbers until 0 is pressed

I have to calculate the arithmetic and geometrical mean of numbers entered by the user in C language. The algorithm works fine, but I don't know how to do the enter numbers until 0 is pressed part. I have tried many things but nothing works. Here is what I have tried to do until now. Thanks for the help.
int main() {
int n, i, m, j, arr[50], sum = 0, prod = 1;
printf("Enter numbers until you press number 0:");
scanf("%d",&n);
while (n != 0) {
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
sum = sum + arr[i];
prod = prod * arr[i];
}
}
int armean = sum / n;
float geomean = pow(prod, (float)1 / n);
printf("Arithmetic Mean = %d\n", armean);
printf("Geometric Mean = %f\n", geomean);
getch();
}
Your code is asking for the number of values in advance and subsequently reading that many values. That's not what you were asked to do.
You need to ask for numbers in a loop and exit the loop when the number that you read is 0. You don't even need an array:
int n = 0, i, m, j, sum=0, prod=1;
while (1) {
int value;
scanf("%d",&value);
if (value == 0) {
break;
}
sum=sum+value;
prod=prod*value;
n++;
}
int armean=sum/n;
float geomean=pow(prod,(float) 1/n);
You have to break the for loop when value 0 entered; so you should check for arr[i].
While loop is not required.
Please go through below code; this could be help full:
#include <stdio.h>
int main()
{
int n, i, m, j, arr[50], sum=0, prod=1;
printf("Enter numbers until you press number 0:");
for(i=0; i<50; i++)
{
scanf("%d",&arr[i]);
if (arr[i] == 0)
{
break;
}
sum=sum+arr[i];
prod=prod*arr[i];
}
printf ("%d %d\n",sum, prod);
n = i+1;
int armean=sum/n;
float geomean=pow(prod,(float) 1/n);
printf("Arithmetic Mean = %d\n",armean);
printf("Geometric Mean = %f\n",geomean);
getch();
return 0;
}
what dbush said is right, you don't need array and are not asking the number in advance but what he did not tell is how can you find the number of values
int main()
{
int n, sum=0, prod=1, num;
printf("Enter numbers until you press number 0:\n");
for(n=0; ; n++)
{
scanf("%d",&num);
if(num==0)
break;
sum=sum+num;
prod=prod*num;
}
printf("sum is %d \n",sum);
printf("prod is %d \n",prod);
printf("n is %d \n",n);
float armean=sum/n; //why int?
float geomean=pow(prod,(float) 1/n);
printf("Arithmetic Mean = %d\n",armean);
printf("Geometric Mean = %f\n",geomean);
//getch(); why getch(), you are not using turboc are you?
}
There is no need for an array, but you should test if the number entered in 0 after reading it from the user. It would be better also to use floating point arithmetic to avoid arithmetic overflow, which would occur quickly on the product of values.
In any case, you must include <math.h> for pow to be correctly defined, you should test the return value of scanf() and avoid dividing by 0 if no numbers were entered before 0.
#include <stdio.h>
#include <math.h>
int main() {
int n = 0;
double value, sum = 0, product = 1;
printf("Enter numbers, end with 0: ");
while (scanf("%lf", &value) == 1 && value != 0) {
sum += value;
product *= value;
n++;
}
if (n > 0) {
printf("Arithmetic mean = %g\n", sum / n);
printf("Geometric mean = %g\n", pow(product, 1.0 / n));
getch();
}
return 0;
}

Why is my average not the correct answer? (C code program to find mean)

I am bashing my head because I cannot figure out why my C code keeps printing the wrong average of a set of n numbers!
This is my code below:
int main()
{
int i;
int n;
int sum = 0.0;
int lowest;
int highest;
float average;
int range;
int middle;
double median;
printf("\nEnter the amount of numbers you want?\n");
scanf("%d",&n);
int numbs[n];
int temp[n];
for(i = 0;i < n; i++)
{
printf("\nEnter a number from 0 to 15: ");
scanf("%d",&temp[i]);
}
while (temp[i] < 0 || temp[i] > 15) than 15
{
printf("This number is not from 0 to 15! Please re-enter another number: ");
scanf("%d",&temp[i]);
}
numbs[i] = temp[i];
sum += numbs[i];
}
int sortt = 0, j, x;
for (x = 1; x < n; x++) {
for (j = 0; j < n - x; j++) {
if (numbs[j] > numbs[j + 1]) {
sortt = numbs[j];
numbs[j] = numbs[j + 1];
numbs[j + 1] = sortt;
}
}
}
lowest = numbs[0];
highest = numbs[n-1];
middle = n/2;
if (n % 2)
{
median = numbs[middle];
}
else
{
median = (numbs[middle - 1] + numbs[middle]) / 2.0;
}
average = sum/n;
range = highest - lowest;
printf("\nSum: %d", sum);
printf("\nAverage: %.2f", average);
printf("\nMedian: %.2f", median);
printf("\nRange: %d\n", range);
return 0;
}
This is my input and output below. You can see that 8 divided by 3 is not 2, it is 2.67! I've tried using double and float.
Input & Output:
You need to correct the following line:
average = sum/n;
to
average = (float)sum/n;
You have to cast your return value into float. Think about it as a function with the following definition:
float divide(int x,int y){
return x/y; // returns an integer instead of float.
}
While this definition:
float divide(int x,int y){
return (float)x/y; // creates a temporary float variable and returns it immediately as the returned value of the function.
}
In addition, declaring int sum=0.0 is definitely going to show you a warning when compiling with -Wall. Try to follow warnings that you get from your compiler and fix all of them before you run your program.
8 divided by 3 is 2, remainder 2. 8 and 3 are integers, and when you divide two integers, you use integer division with integer rules.
Also, this line might be confusing you:
int sum = 0.0;
Since sum is an int, this just sets sum to zero.
And:
average = sum/n;
Since both sum and n are integers, this is integer division. What you do with a result does not affect how that result is computed -- C's rules are complex enough already.
/*Here see you can intake all values as float instead */
#include <stdio.h>
#include <stdlib.h>
void main()
{
float i,n,a,b,sum,ave;
printf("This is a program to calculate the average of 'n' numbers \n");
printf("Of How many numbers do you want to calculate average \n");
scanf("%f", &n);
printf("Enter the first number \n");
scanf("%f", &a);
sum = a;
for (i=1;i<n;i++)
{
printf("Enter another number \n");
scanf("%f", &b);
sum = sum + b;
}
ave = (sum/n);
printf("The average of the %f number is %f", n, ave);
getchar();
}

Dynamic Programming - Minimum Coin caching

Earlier I posted a question about the coin vending machine problem (the minimum number of coins required). Turns out the issue was a typo in a for loop, so now the program works. The original question was this:
As the programmer of a vending machine controller your are required to compute the minimum number of coins that make up the required change to give back to customers. An efficient solution to this problem takes a dynamic programming approach, starting off computing the number of coins required for a 1 cent change, then for 2 cents, then for 3 cents, until reaching the required change and each time making use of the prior computed number of coins. Write a program containing the function ComputeChange(), that takes a list of valid coins and the required change. This program should repeatedly ask for the required change from the console and call ComputeChange() accordingly. It should also make use of “caching”, where any previously computed intermediate values are retained for subsequent look-up.
The issue is that the code makes use of recursion, so it takes quite a long time to evaluate large values. Making use of caching should improve the issue, but I have no idea how to go about it. The code can be found below.
#include <stdio.h>
#include <limits.h>
int computeChange(int[],int,int);
int min(int[],int);
int main(){
int cur[]={1,2,5,10,20,50,100,200};
int n = sizeof(cur)/sizeof(int);
int v;
printf("Enter a value in euro cents: ");
scanf("%d", &v);
printf("The minimum number of euro coins required is %d", computeChange(cur, v, n));
return 0;
}
int computeChange(int cur[], int v, int n){
if(v < 0)
return INT_MAX;
else if(v == 0)
return 0;
else{
int possible_mins[n], i;
for(i = 0; i < n; i++){
possible_mins[i]=computeChange(cur, v-cur[i], n);
}
return 1+min(possible_mins, n);
};
}
int min(int a[], int n){
int min = INT_MAX, i;
for(i = 0; i < n; i++){
if((a[i]>=0) && (a[i]< min))
min = a[i];
}
return min;
}
With your existing code:
#include <stdio.h>
#include <limits.h>
int computeChange(int[],int,int);
int min(int[],int);
void initChange ();
int change [MAX]; //used for memoization
int main(){
int cur[]={1,2,5,10,20,50,100,200};
int n = sizeof(cur)/sizeof(int);
int v;
initChange ();
printf("Enter a value in euro cents: ");
scanf("%d", &v);
printf("The minimum number of euro coins required is %d", computeChange(cur, v, n));
return 0;
}
void initChange () {
int i =0;
for (i = 0; i < MAX; i++) {
change[i] = INT_MAX;
}
}
int computeChange(int cur[], int v, int n){
if(v < 0)
return INT_MAX;
else if(v == 0)
return 0;
else{
if (change[v] == INT_MAX) {
int possible_mins[n], i;
for(i = 0; i < n; i++){
possible_mins[i]=computeChange(cur, v-cur[i], n);
}
change[v] = 1 + min(possible_mins, n); // memoization
}
return change[v];//you return the memoized value
};
}
int min(int a[], int n){
int min = INT_MAX, i;
for(i = 0; i < n; i++){
if((a[i]>=0) && (a[i]< min))
min = a[i];
}
return min;
}
I already posted a solution using loops in your previous question. I will post it again here:
So the below is the code snippet for your problem using memoization and dynamic programming. The complexity is O(Val*numTypesofCoins).
In the end, change[val] will give you the min number of coins for val.
int main (void) {
int change [MAX];
int cur[]={1,2,5,10,20,50,100,200};
int n = sizeof(a)/sizeof(int);
int val; //whatever user enters to get the num of coins required.
printf("Enter a value in euro cents: ");
scanf("%d", &val);
for (i=0; i <= val; i++) {
change[i] = INT_MAX;
}
for (i=0; i < n; i++) { // change for the currency coins should be 1.
change[cur[i]] = 1;
}
for (i=1; i <= val; i++) {
int min = INT_MAX;
int coins = 0;
if (change[i] != INT_MAX) { // Already got in 2nd loop
continue;
}
for (j=0; j < n; j++) {
if (cur[j] > i) { // coin value greater than i, so break.
break;
}
coins = 1 + change[i - cur[j]];
if (coins < min) {
min = coins;
}
}
change[i] = min;
}
}

Custom Recursive function |returning no values at all| in C

I thought of making this An=8(An-1)*(An-1)/An-2 while a1=1,a0=1
With the following code for n=2 a2=0.0000 which is altogether wrong
On the other hand (Sum of An) S(n)=1+1+0.0000(false number) theoretically correct
#include <stdio.h>
float rec(int n);
float sum(int n);
main()
{
int n;
printf("\nInput N of term an: ");
scanf("%d",&n);
printf("\n\na%d=%f",n,rec(n));
printf("\n\nS(%d)=%f",n,sum(n));
}
float rec(int n)
{
int i;
float a[1000]={1,1};//a0=1,a1=1
if(n<0)
printf("\nNegative values of N are invalid");
else if(n==0)
return a[0];
else if(n==1)
return a[1];
else if(n>1)
for(i=2;i<=n;i++)
a[i]=((8 * a[i-1]*a[i-1]) - 1)/a[i-2];
return a[i];
}
float sum(int n)
{
int i;
float sum=0;
for(i=0;i<=n;i++)
sum+=rec(i);
return sum;
}
float a[1000]={1,1};
initializes a[0] = 1 and a[1] = 1 and rest of the elements to 0.
Now, you are returning a[i] from your function. For n=2 it will return a[3], which is 0 of course, but not the a[2] as you are expecting.
Now just change the return value to a[i-1] and it will work.
float rec(int n)
{
int i;
...
...
return a[i-1];
}
for(i=2;i<=n;i++)
a[i]=((8 * a[i-1]*a[i-1]) - 1)/a[i-2];
return a[i];
problem here, you will always get zero!!! why?
say i input 3,, now say i = 3,alls well a[3] gets calcualted, now you program goes back to the for loop, now i =4, it now does not fit the check i<=n, and so now i is 4,
you are returning a[i] which is actually a[myanswer+1]...
fix it by returning a[i-1]
At this point in rec:
return a[i];
i is 3, not 2, because it was incremented before the last test of the loop. As such you're returning the element of the array after the last one set. Be careful if you fix this by returning a[i-1] because if i is never initialized or is 0, this will cause a problem. You should clean up the rec method a bit to handle these corner cases, but the immediate problem is that i is 3, not 2.
Replace
return a[i];
with
return a[n];
(As an aside, you do not need the extra branches for 0 and 1.)
A beautiful example of Schlemiel the Painter's algorithm :)
About half the computations are done unnecessarily multiple times
The array is unnecessary and defeats the whole point of using a recursive approach
Beside, it is defined to hold 1000 values, but the function grows so fast that it will exceed a float capacity after 10 terms or so.
A more streamlined version here :
#include <stdio.h>
float A (int n, float * sum)
{
if (n <= 0) { *sum = 0; return 0; }
if (n == 1) { *sum = 1; return 1; }
if (n == 2) { *sum = 2; return 1; }
float anm2 = A(n-2, sum); // store A(n-2). sum will be overwritten by A(n-1)
float anm1 = A(n-1, sum); // store A(n-1) once to avoid calling A twice, and get preceding sum
float an = ((8 * anm1*anm1) - 1)/anm2;
*sum += an;
printf ("index %d : term %g sum %g\n", n, an, *sum);
return an;
}
int main (void)
{
int n;
float sum;
printf("\nInput N of term an: ");
scanf("%d",&n); printf("\n");
printf("\na%d=%f",n,A(n, &sum));
printf("\n\nS(%d)=%f",n,sum);
}
Beside, recursion is unnecessary and leads to inefficient and confusing code.
See a more straightforward solution here:
#include <stdio.h>
typedef struct {
float term;
float sum;
} A; // current term and sum of series A
void compute_A (int n, A * res)
{
int i;
float anm1, // a[n-1]
anm2; // a[n-2]
// special case for n<=1
if (n == 1)
{
res->sum = res->term = 1;
return;
}
if (n <= 0)
{
res->sum = res->term = 0;
return;
}
// initial terms
anm2 = anm1 = 1;
// initial sum
float sum = anm1+anm2;
// compute the remaining n-2 terms and cumulate the sum
for (i = 2 ; i <= n ; i++)
{
// curent term
float an = ((8 * anm1*anm1) - 1)/anm2;
// cumulate sum
sum += an;
// shift computation window
anm2 = anm1;
anm1 = an;
printf ("index %d : term %g sum %g\n", i, an, sum);
}
// report result
res->sum = sum;
res->term = anm1;
}
int main (void)
{
int n;
A res;
printf("\nInput N of term an: ");
scanf("%d",&n); printf("\n");
compute_A (n, &res);
printf("\na%d=%f",n,res.term);
printf("\n\nS(%d)=%f",n,res.sum);
}
float rec(int n){
static max_i = 1;
static float a[1000]={1,1};//a0=1,a1=1
int i;
if(n<0){
printf("\nNegative values of N are invalid");
return NAN;//<math.h>
}
if(n >= 1000){
printf("\nMore than 1000 are invalid");
return NAN;
}
if(n<2)
return a[n];
if(n>max_i){
for(i=max_i+1;i<=n;++i)
a[i]=((8 * a[i-1]*a[i-1]) - 1)/a[i-2];
max_i = n;
return a[n];
}
return a[n];
}

Resources