How to find max&min in while loop - c - 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.

Related

Get evenly spaced numbers in a range, in 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
}

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

C - Getting the min and max of the randomly generated numbers

My code is below, this is my first programming course so expect a possibly stupid mistake.
Basically I am trying to get the min/max and the position number of them. However, my max works correctly up until 6 numbers are generated and I can't seem to understand why.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n, r, x, i;
int max, min;
int num[0];
printf("Enter an integer");
scanf("%d", &n);
x = n;
printf("\n Pos | Val");
for(n=0; n<x; n++)
{
r = ( rand()%1000 ) + 1;
printf("\n %3d | %3d", n+1, r);
}
max=num[0];
i=0;
while(i<x) // while loop determing the biggest number
{
if(num[i]>max)
{
max=num[i];
}
i++;
}
printf("\nMax : %d",max); // biggest number
return 0;
}
There are actually several places that needs improvement in your code.
Firstly, it is invalid to declare an array of size 0 in your code int num[0];, so I'm not sure why your code work with a n up to 6.
Secondly, as you may learn very soon, indentation is very important while programming so that the code is better to understand and maintain in the future. Furthermore, while C is not a language that requires indentation (and that is considered one of its strengths) many common languages such as Python that rely on whitespace to differentiate functions do need careful management of indentation.
Third, RAND_MAX is not a multiple of 1000 so you would not obtain equal probability in your program. A srand function call is also recommended.
A possible implementation of your intended program (still ugly):
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAXN 1000
int main(void) {
int n, r, i;
int pos = 0;
int max;
int num[MAXN];
printf("Enter an integer");
scanf("%d", &n);
srand(time(0));
printf("\n Pos | Val");
for (i = 0; i<n; i++)
{
r = (int)(((double)rand() / (RAND_MAX + 1)) * 1000) + 1;
printf("\n %3d | %3d", i + 1, r);
num[i] = r;
}
max = num[0];
i = 0;
for (i = 1; i < n; i++)
{
if (num[i] > max)
{
max = num[i];
pos = i;
}
}
printf("\nMax : %d | Pos : %d", max, pos); // biggest number
//while (1);
return 0;
}
As far as my tests, this piece works well
As already identified by numerous answers and comments, your primary problem is your array. Standard C doesn't allow array sizes of zero. GCC does unless you tell it to complain.
However, all the other answers continue to blithely use the array. For the problem stated, there's no need for an array at all. Also, the question text mentions 'minimum' as well as 'maximum', and 'position' as well as 'value' — though the code shown reports neither minimum nor position. Clearly, if this is just a preliminary phase before using the data for some other work, then you probably do need to save the data in an array. You can then decide whether to use a C99 (or later) VLA — variable length array — or whether to use dynamic memory allocation with malloc() et al, remembering to free the allocated space with free().
Here's a simple revised program that doesn't use an array and does manage minimum and maximum as well as reporting positions. It deliberately changes the range of values to 0..999 so that there are never 4-digit numbers to throw the presentation off. You can decide what to do if you absolutely must used 1-based counting and values in the range 1..1000. (Using + 1 in selected locations is one part of the answer; deciding to replace %3d with either %d or %4d is probably the rest of the answer).
This code uses the time as a seed value for the random numbers, and it reports that seed value. If the program was going to be used seriously, I'd make it accept optional arguments, one of which would be the seed, so that previous runs can be recreated. I'd probably make it accept an argument for the number of random values to be generated too.
The code validates that a number was entered and validates that the number falls in the range 1..999, bailing out with an error message written to standard error if the value is not acceptable. Note that the error message diagnoses what is valid — there is nothing more frustrating than to be told that something is invalid but not why and what you need to do to fix it (and often, it helps to show what the program read — it might not be what the user thought the program would read).
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int n;
printf("Enter number of random values to test: ");
if (scanf("%d", &n) != 1 || n <= 0 || n >= 1000)
{
fprintf(stderr, "Didn't read a valid number in the range 1..999\n");
return 1;
}
unsigned seed = time(0);
srand(seed);
printf("Seed: %u\n", seed);
int minval = 0;
int maxval = 0;
int minidx = 0;
int maxidx = 0;
printf("\n Pos | Val\n");
for (int i = 0; i < n; i++)
{
int r = (rand() % 1000);
printf(" %3d | %3d\n", i, r);
if (i == 0)
{
minval = r;
maxval = r;
minidx = i;
maxidx = i;
}
else if (r > maxval)
{
maxval = r;
maxidx = i;
}
else if (r < minval)
{
minval = r;
minidx = i;
}
}
printf("Minimum value was %3d at index %3d\n", minval, minidx);
printf("Maximum value was %3d at index %3d\n", maxval, maxidx);
return 0;
}
Example run (program mnmx67 compiled from mnmx67.c):
$ mnmx67
Enter number of random values to test: 10
Seed: 1503763592
Pos | Val
0 | 201
1 | 216
2 | 85
3 | 793
4 | 382
5 | 780
6 | 341
7 | 661
8 | 75
9 | 266
Minimum value was 75 at index 8
Maximum value was 793 at index 3
$
You did not store your random numbers in num, also You need to have some space to store these numbers. Try this for size, i commented my changes
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n, r, x, i;
int max, min;
int * num; // ++++++++ pointer to array
printf("Enter an integer");
scanf("%d", &n);
x = n;
num = malloc(x * sizeof(int)); // ++++++++++ allocate memory
printf("\n Pos | Val");
for(n=0; n<x; n++)
{
r = ( rand()%1000 ) + 1;
printf("\n %3d | %3d", n+1, r);
num[n] = r; // +++++++++ store your number
}
max=num[0];
i=0;
while(i<x) // while loop determing the biggest number
{
if(num[i]>max)
{
max=num[i];
}
i++;
}
printf("\nMax : %d",max); // biggest number
free(num); // +++++++++ free memory
return 0;
}
Your first mistake is that the array's dimension is zero. You need to set a size for the array.
I would do this by splitting the code into three additional functions: one to generate the numbers, and two others to find the min and max.
int *gennums(size_t n)
{
int *nums;
size_t i;
if ((nums = malloc(n * sizeof (int))) != NULL) {
for (i = 0; i < n; ++i)
nums[i] = rand() % 1000;
return nums; // caller must free
}
return NULL;
}
int min(const int *arr, size_t n)
{
assert(n > 0);
int m = arr[0];
size_t i;
for (i = 0; i < n; ++i)
if (arr[i] < m)
m = arr[i];
return m;
}
int max(const int *arr, size_t n)
{
assert(n > 0);
int m = arr[0];
size_t i;
for (i = 0; i < n; ++i)
if (arr[i] > m)
m = arr[i];
return m;
}
Here int num[0];
You are not storing your random numbers in this array.Searching in that is meaning less.
Also size of your array should be at-least equal to n

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

Add n Integers to an non fixed Array

I've been looking for a solution quite a while now, but did not manage to find anything.
I need a program which takes the users input (a random amount of integers) until EOF, sums them up and gives me back the average.
I tried it using an array but I am not sure whats my mistake here.
I managed to get it working with a fixed size array. But I need a flexible one.. Is this even possible?
Here is what I got so far:
#include <stdio.h>
int main()
{
int count = 3;
int numbers[count];
long sum;
float average;
int i;
for (i = 0; i < count; i++) {
while (scanf("%d", &numbers[i]) != EOF) {
sum += numbers[i];
}
}
average = (float)sum/count;
printf("Average of your numbers is: %.2f\n",average);
return 0;
}
If you're just trying to find the average then you don't need to actually store these numbers.
int count = 0;
int sum = 0;
int num = 0;
double avg = 0.0;
for(; scanf("%d", &num) != EOF; sum += num, count++)
;
avg = sum / count;
After checking with OP, he does not mind if the inputs are not stored in array. In that case, you may want to consider this:
int num=0;
int sum=0
int count=0;
do
{
printf("Enter number:");
scanf("%d", num);
sum += num;
count++;
printf("Proceed(y/n)?");
scanf("%c", proceed);
}while(proceed == 'y');
This code may be a little troublesome that you need to enter 'y' to continue inputing, but this may solve your current problem of inputting n inputs.
You will need to realloc the size of the array if you have filled the existing array. This should work:
#include <stdio.h>
#include <stdlib.h>
int main() {
int input;
int size = 0;
int* arr = NULL;
int* temp = NULL;
long sum = 0;
float average = 0;
do {
scanf("%d", &input);
size++;
temp = (int*) realloc(arr, sizeof(int)*size);
if(temp != NULL) {
arr = temp;
arr[size-1] = input;
}
sum += input;
} while(input != 0);
average = sum / size;
printf("sum: %lu\n", sum);
printf("average: %f\n", average);
return 0;
}
It does not have to be an array if all you're doing is adding up numbers
int number = 0;
int count = 0;
while(scanf("%d", &number)!=EOF)
{
sum += number;
count++;
}
Also this will never work because count is supposed to be a constant
int count = 3;
int numbers[count];

Resources