MAX AND MIN IN RANDOM NUMBER - c

I need to write a C program to :
1. fills a 20 elementary array(marks) with random numbers between 0 and 100
2. print the number out 8 to a line.
3. Prints out the max and min and the average of the numbers.
I wrote following program and every thing is ok except min, I dont know how could I do it any help or tips would be really appreciates.
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main(void)
{
int i = 0;
int sum = 0;
int avg = 0;
int min = 0;
int max = 0;
int x = 0;
int random = 0;
int num[20] = { 0 };
srand(time(NULL));
for (x = 0; x<20; x++)
{
random = rand() % 100 + 1;
num[x] = random;
if (num[x]>max)
{
max = num[x];
}
if (x % 8 == 0)
{
printf("\n");
}
sum += random;
printf("%d\t", num[x]);
}
avg = sum / 20;
printf("\n\nthis is Max number: %d", max);
printf("\nThis is average number:%d", avg);
printf("\nThis is min number:", min);
return 0;
}

You have a condition in your code which determines the maximum value. You need a same for finding the minimum value too,i.e,Something like this:
if (num[x]<min)
{
min = num[x];
}
But this will never be true as min is 0 and num[x] will always be greater than 0. So set min to 100 by changing
int min = 0;
To
int min = 100;
But still,your code won't work as expected. This is because you forgot to add a format specifier(%d) in your last printf. So change
printf("\nThis is min number:", min);
To
printf("\nThis is min number:%d", min);
And finally,your code will work!

Related

is there any problem in my minimum number finding?

The code is to find maximum and minimum number, so i make this code
// find maximum and minimum in array
#include <stdio.h>
int main () {
int values[5]; // I take the size of array as 5
int i, max = values[0], min = values[0]; // and gives max and min 0
// index position in the array
printf ("Enter 5 numbers: ");
for (i = 0; i < 5; i++) {
scanf ("%d", &values[i]);
}
for (i = 0; i < 5; i++) {
if (values[i] < min) {
min = values[i];
}
if (values[i] > max) {
max = values[i];
}
}
printf ("The maximum number is: %d", max);
printf ("\nThe minimum number is: %d", min);
return 0;
}
everything is fine maximum showing the maximum value but the minimum showing always 0. I need to put values in minus to show minimum values. help please.

Find the maximum, minimum, and average values in the array

In my code, the program will not allowed the negative number entered, the program will stop reading, then calculate the maximum value, minimum value and average value.
That is my code
#include <stdio.h>
int main(void) {
int age[10] = {0}; // initalized an array
printf("Please enter ages: \n"); // allow user to enter numbers
for (int i = 0 ;i < 10; i++) {
scanf("%d",&age[i]);
if (age[i] < 0) { // if it is negative number, it is should stop reading
break;
}
else if (age[i] >= 0) {
continue;
}
}
int maximum = age[0];
int minimum = age[0];
float average = 0.0;
int length = sizeof(age) / sizeof(age[0]);
for (int j = 0; j < length; j++) {
if (maximum < age[j]) {
maximum = age[j];
}
else if (minimum > age[j]) {
minimum = age[j];
}
average += age[j];
}
average = average / length;
printf("%d\n", maximum);
printf("%d\n", minimum);
printf("%.1f\n", average);
return 0;
}
Please enter ages: 5 -1
expected result: max:5;min:5,average:5;
actual result: max:5;min:-1,average: 0.4;
That was a question that I met, the code should not accept any negative value.
Thank you all.
but if I add age[i] = 0; then break;
The average value will equal to 0.5.
You don't need an array.
You don't need both a loop variable and a length.
It's more appropriate to use ? : for updating minimum/maximum.
You don't need two loops
You need to check the int return value of scanf(), which indicates the number of items successfully scanned, so it should be 1. I'll leave that for you/OP to add (hint: replace for-loop by while-loop to avoid having to add a separate length variable again).
int main(void)
{
printf("Please enter ages: \n");
int minimum = INT_MAX;
int maximum = 0;
int sum = 0;
int count = 0;
for (count = 0; count < 10; count++)
{
int age;
scanf("%d", &age);
if (age < 0)
{
break;
}
sum += age;
minimum = (age < minimum) ? age : minimum;
maximum = (age > maximum) ? age : maximum;
}
if (count > 0)
{
printf("Min: %d\n", minimum);
printf("Max: %d\n", maximum);
printf("Avg: %.1f\n", (float)sum / count);
}
else
{
printf("You didn't enter (valid) age(s).\n");
}
return 0;
}
Your approach is overly complicated and wrong.
You want this:
...
int length = 0; // declare length here and initialize to 0
for (int i = 0; i < sizeof(age) / sizeof(age[0]); i++) {
scanf("%d", &age[i]);
if (age[i] < 0) // if it is negative number, it is should stop reading
break;
length++; // one more valid number
}
// now length contains the number of numbers entered
// the rest of your code seems correct
You also might need to handle the special case where no numbers are entered, e.g: the only thing entered is -1. It doesn'make sense to calculate the average or the largest/smallest number when there are no numbers.
A possible solution could be:
(corrections are written in the commented code)
#include <stdio.h>
int main(void){
int arraySize = 10;
int age[arraySize]; //initialize not required
//the number of existing values inside the array (effective length)
int length = 0;
printf("Please enter ages: \n"); // allow user to enter numbers
for(int i=0; i<arraySize; i++){
scanf("%d",&age[i]);
// if it is negative number, it is should stop reading
if(age[i]<0){ break; }
//the else-if is not required
//but, if the compiler goes here,
//it means that the value is acceptable, so
length++;
}
int maximum = age[0];
int minimum = age[0];
float average = 0.0;
for(int j=0; j<length; j++){
if(maximum<age[j]){ maximum = age[j]; }
else if(minimum>age[j]) { minimum = age[j]; }
average += age[j];
}
average = average / length;
printf("%d\n", maximum);
printf("%d\n", minimum);
printf("%.1f\n", average);
return 0;
}
OP's primary problem is the 2nd loop iterates 10 times and not i times (the number of times a non-negative was entered.
For fun, let us try a non-floating point solution as it really is an integer problem.
An array to store values is not needed.
#include <limits.h>
#include <stdio.h>
int main(void) {
// Keep track of 4 things
int min = INT_MAX; // Set min to the max int value.
int max = INT_MIN;
long long sum = 0; // Use wide type to cope with sum of extreme ages.
int count = 0;
#define INPUT_N 10
printf("Please enter ages: \n");
for (count = 0; count < INPUT_N; count++) {
int age;
if (scanf("%d", &age) != 1) {
fprintf(stderr, "Missing numeric input.");
return EXIT_FAILURE;
}
if (age < 0) {
break;
}
if (age < min) min = age;
if (age > max) max = age;
sum += age;
}
if (count == 0) {
fprintf(stderr, "No input.");
return EXIT_FAILURE;
}
printf("Maximum: %d\n", max);
printf("Minimum: %d\n", min);
// Could use FP and
// printf("Average: %.1f\n", 1.0 *sum / count);
// But for fun, how about a non-FP approach?
#define SCALE 10
#define SCALE_LOG 1
sum *= SCALE; // Scale by 10 since we want 1 decimal place.
// Perform a rounded divide by `count`
long long average_scaled = (sum + count/2) / count;
// Print the whole and fraction parts
printf("Average: %lld.%.*lld\n",
average_scaled / SCALE, SCALE_LOG, average_scaled % SCALE);
return 0;
}
First of all, you must record how many positive numbers you enter. Then the value of length will be correct.
Second, for the second for loop, j must be smaller than the number of positive ages. Therefore, you won't add negative age[j] to average.
You can simply modify the second for loop.
#include <stdio.h>
int main(void) {
int age[10] = {0}; // initalized an array
printf("Please enter ages: \n"); // allow user to enter numbers
int length = 0;
for (int i = 0 ;i < 10; i++) {
scanf("%d",&age[i]);
if (age[i] < 0) { // if it is negative number, it is should stop reading
break;
}
else if (age[i] >= 0) {
length++;
continue;
}
}
int maximum = age[0];
int minimum = age[0];
float average = 0.0;
for (int j = 0; j < length; j++) {
if (maximum < age[j]) {
maximum = age[j];
}
else if (minimum > age[j]) {
minimum = age[j];
}
if ( age[j] > 0.0 )
{
average += age[j];
}
}
average = average / length;
printf("%d\n", maximum);
printf("%d\n", minimum);
printf("%.1f\n", average);
return 0;
}

Min and max in C using basics

This program is supposed to end when the user enters 0 and then show the count, sum, average, min and max. I am able to figure out the sum count and average but my min and max isn't working.
int main()
{
int number = 0;
int count = 0;
int sum = 0;
int average;
int min = 0;
int max = 0;
do {
printf("Enter a number: ");
scanf_s("%d", &number);
if (number > 0)
{
count = count + 1;
sum += number;
min = number;
max = number;
}
average = sum / count;
if (number < min)
{
min = number;
}
else if (number > max)
{
max = number;
}
} while (number != 0);
printf("count: %d\n", count);
printf("Sum: %d\n", sum);
printf("average: %d\n", average);
printf("Minimum: %d\n", min);
printf("Maximum: %d\n", max);
system("pause");
}
First, initialize min and max with proper values.
int min = INT_MAX;
int max = INT_MIN;
Second, update min only when the input number less than current min.
Update max only when the input number is greater than the current max.
int main()
{
int number = 0;
int count = 0;
int sum = 0;
int average;
int min = INT_MAX; // don't forget to include limits.h
int max = INT_MIN;
do {
printf("Enter a number: ");
scanf_s("%d", &number);
if (number > 0)
{
count = count + 1;
sum += number;
if (number < min)
{
min = number;
}
if (number > max)
{
max = number;
}
}
else if (number < 0)
{
printf("Negative value entered...skipping");
}
} while (number != 0);
printf("count: %d\n", count);
printf("Sum: %d\n", sum);
average = sum / count;
printf("average: %d\n", average);
printf("Minimum: %d\n", min);
printf("Maximum: %d\n", max);
system("pause");
}
You need to do two things:
Remove min = number; and max = number from the check number > 0. This is because, you are overriding the variables with the number value. This will lead to loss of previous min and max values, if any.
Instead of int min = 0; and int max = 0, use the upper and lower
limit for integer data type. That is present in limits.h. You can use INT_MAX (2147483647) and INT_MIN (–2147483648).
There is another problem with your code. instead of else if (number > max), it should be if (number > max). For every number you need to check for both min and max values.
Also, the condition if (number > 0) should instead be if (number != 0). This is because you want the program to end when user enters
0, so for it to accept negative numbers that condition has to be
changed.
Also, you need not calculate average every single time. Instead
you can calculate after coming out of the loop.
Also, you need to move the checks for min and max inside the check
number != 0. The reason for this is that you don't want to calculate min and max when number == 0.
You used:
if (number > 0)
{
count = count + 1;
sum += number;
min = number;
max = number;
}
Here, don't use:
min = number;
max = number;
Because, when number is greater than 0, min and max value will be set to the input number so the if and else if statement below it, will not work.
Set the first number that scanf reads as initial value of min and initial value of max;This will always work whatever the numbers are.
if (count==1)
{
min=number;
max=number;
}

C language- How to print out the largest number inputted into an array?

I want to be able to print out the largest age inputted by the user as well as the smallest age.
Also, I noticed my program doesn't include the numbers after the decimal point. It would just say 25.00 for example, rather than 25.25.
Any help is greatly appreciated!
#include "stdafx.h"
#include "stdio.h"
void main()
{
int age[11];
float total = 0;
int i = 1;
float average;
do
{
printf("# %d: ", i);
scanf_s("%d", &age[i]);
total = (total + age[i]);
i = i + 1;
} while (i <= 10);
average = (total / 10);
printf("Average = %.2f", average);
}
I think it will be helpful.
For decimal point you have to declare your array as float.
FLT_MAX These macros define maximum value of a float. Before useing FLT_MAX you should inclue float.h header file.
#include <stdio.h>
#include <float.h>
int main(void)
{
float age[11];
float total = 0;
int i = 1;
float average;
float largestInput = 0.0;
float smallestInput = FLT_MAX;
do
{
printf("# %d: ", i);
scanf("%f", &age[i]);
total = total + age[i];
//here i am checking the largest input
if (age[i]> largestInput){
largestInput = age[i];
}
//here i am checking the smallest input
if (age[i] < smallestInput) {
smallestInput = age[i];
}
i = i + 1;
} while (i <= 10);
average = (total / 10);
printf("Average = %.2f\n", average);
printf("Largest Input Is = %.2f\n", largestInput);
printf("Smallest Input IS = %.2f", smallestInput);
return 0;
}
Pseudo-code. Keep two extra variables.
long largestInput, smalltestInput.
set
largestInput = smalltestInput = age[0];
for (i = 0; i < 10; i++) {
if age[i]> largestInput{
largestInput = age[i];
}
if age[i] < smallestInput {
smalltestInput = age[i];
}
}
Print it as you like
Your code works fine on my system. I've modified your code to not be Windows specific and shown you how to calculate the smallest and largest of the numbers entered. The idea is to constantly compare the current entry to the current smallest and largest number and change smallest and largest as needed. The code below also shows how to start at array index 0.
#include <stdio.h>
int main()
{
int age[10];
float total = 0;
int i = 0;
float average;
int large = -9999;
int small = 9999;
do
{
printf("# %d: ", i+1);
scanf("%d", &age[i]);
total = (total + age[i]);
if( age[i] < small )
{
small = age[i];
}
if( age[i] > large )
{
large = age[i];
}
i++;
} while (i < 10);
average = (total / 10.00);
printf("Smallest = %d Largest = %d \n", small, large);
printf("Average = %.2f\n", average);
}
# 1: 30
# 2: 40
# 3: 50
# 4: 2
# 5: 3
# 6: 4
# 7: 6
# 8: -1
# 9: 4
# 10: 5
Smallest = -1 Largest = 50
Average = 14.30

Fill a defined 2D Array with random numbers in C / Average / Max Value

I've created this 2D 21x21 array that has all it's values set to -1. I wrote it to print the address and value and somehow it only starts at [6][19] why?
What i want to do is to replace some of the -1 values with random numbers from 0 to 100 in the same array. I know i need to seed it with srand but i'm having problems connecting the functions since i'm a total beginner in C.
EDIT 1:
Now i can print the whole array and fill it with random numbers. For the -1 values i just assigned directly which for this case its fine.
What i'm trying now is finding the average of all the values and the maximum number, so what i have is:
#include<stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int a[21][21], i , j;
for (i = 0; i < 21; i++)
{
for ( j = 0; j < 21; j++)
{
a[i][j] = GetRand(0, 100);
a[7][15] = -1;
a[10][6] = -1;
a[13][5] = -1;
a[15][17] = -1;
a[17][17] = -1;
a[19][6] = -1;
printf("%3d" , a[i][j]);
}
printf("\n");
}
return 0;
}
// random seed
int GetRand(int min, int max);
int get() {
int i, r;
for (i = 0; i < 21; i++)
{
r = GetRand(0, 100);
printf("Your number is %d \n", r);
}
return(0);
}
int GetRand(int min, int max)
{
static int Init = 0;
int rc;
if (Init == 0)
{
srand(time(NULL));
Init = 1;
}
rc = (rand() % (max - min +1) +min);
return (rc);
}
// average
int avg()
float sum=0.0;
for(i = 0; i <= 21; i = i + 1) {
for(j = 0; j <= 21; j = j + 1){
sum = sum + a[21][21];
}
printf("The the average number is %.2f\n", sum/21);
}
//find maximum of all values
int *pv = &a[0][0];
max = min = 0;
for (i = 1; i < i*j; ++i){
if (pv[i] > pv[max])
max =i;
if (pv[i] < pv[min])
min = i;
}
printf("The max value is %d in row %d, col %d\n", pv[max], max/j, max%j);
return 0;
}
For the average function the compiler tells me that expected a declaration before i, which is "float sum=0.0;" but i haven't been able to fix that yet.
For the finding the max function i'm not sure yet what i'm doing there, i just have a vague idea of how it's done...am i going in the right direction?
Thanks!
It's very simple: Just assign the result of your GetRand function to the matrix entry.

Resources