is there any problem in my minimum number finding? - arrays

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.

Related

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

MAX AND MIN IN RANDOM NUMBER

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!

Most frequent element in a sequence using arrays in C

I'm doing an online course on "Programming, Data Structure & Algorithm". I've been given an assignment to "find the most frequent element in a sequence using arrays in C (with some constraints)". They've also provided some test-cases to verify the correctness of the program. But I think I'm wrong somewhere.
Here's the complete question from my online course.
INPUT
Input contains two lines. First line in the input indicates N,
the number of integers in the sequence. Second line contains N
integers, separated by white space.
OUTPUT
Element with the maximum frequency. If two numbers have the
same highest frequency, print the number that appears first in the
sequence.
CONSTRAINTS
1 <= N <= 10000
The integers will be in the range
[-100,100].
And here's the test cases.
Test Case 1
Input:
5
1 2 1 3 1
Output:
1
Input:
6
7 7 -2 3 1 1
Output:
7
And here's the code that I've written.
#include<stdio.h>
int main()
{
int counter[201] = {0}, n, i, input, maximum = 0;
scanf("%d", &n);
for(i = 1; i <= n; i++) {
scanf("%d", &input);
if(input < -100 && input < 100)
++counter[input];
}
maximum = counter[0];
for (i = 1; i < 201; i++) {
if (counter[i] > maximum) {
maximum = counter[i];
}
}
printf("%d", maximum);
return 0;
}
Please tell me where I'm wrong. Thank you.
EDIT:
I've modified the code, as suggested by #zoska. Here's the working code.
#include<stdio.h>
int main()
{
int counter[201] = {0}, n, i, input, maximum = 0;
scanf("%d", &n);
for(i = 1; i <= n; i++) {
scanf("%d", &input);
if(input < 100 && input > 0)
++counter[input + 100];
else
++counter[input];
}
maximum = counter[0];
for (i = 0; i < 201; i++) {
if (counter[i] > maximum) {
maximum = i - 100;
}
}
printf("%d", maximum);
return 0;
}
Additionally to problem pointed out by Paul R is:
You are printing maximum occurrences of number, not the number itself.
You're going to need another variable, which will store the number with maximum occurences. Like :
maximum = count[0];
int number = -100;
for (i = 0; i < 201; i++) {
if (counter[i] > maximum) {
maximum = counter[i];
number = i - 100;
}
}
printf("number %d has maximum occurences: %d", number, maximum);
Also you should iterate through an array from 0 to size-1:
So in all cases of your loops it should be :
for(i = 0; i < 201; i++)
Otherwise you won't be using count[0] and you will only have a range of -99...100.
Try below code
#include<stdio.h>
int main()
{
int counter[201] = {0}, n, i, input, maximum = 0;
scanf("%d", &n);
for(i = 1; i <= n; i++) {
scanf("%d", &input);
if(input >= -100 && input <= 100)
++counter[input + 100];
}
maximum = counter[0];
int index = 0;
for (i = 0; i < 201; i++) {
if (counter[i] >= maximum) {
index = i;
maximum = counter[i];
}
}
printf("number %d occured %d times\n", index-100, maximum);
return 0;
}
I would prefer checking in one loop itself for the maximum value just so that the first number is returned if i have more than one element with maximum number of occurances.
FInd the code as:
#include<stdio.h>
int main()
{
int n,input;
scanf("%d",&n);
int count[201] ={0};
int max=0,found=-1;
for(int i=0;i<n;i++)
{
scanf("%d",&input);
count[input+100]++;
if(max<count[input+100])
{
max= count[input+100];
found=input;
}
}
printf("%d",found);
return 0;
}
But, there is also one condition that if the number of occurance are same for two numbers then the number which appers first in sequence should appear.

c programming regarding arrays and minimum?

Build a program which reads from the user an array with n elements and finds the element with the smallest value.Then the program finds the number of the elements which have an equal value with this minimum.The found element with the smallest value along with the number of the elements which have an equal value with the minimum of the array should be displayed on screen..
I wrote this code :
#include <stdio.h>
int main() {
int n = 1, min = 0, count = 0;
int number[n];
printf("Enter the size of array you want");
scanf("%i", &n);
int x;
for (x = 0; x < n; x++) {
int num;
printf("\nEnter a Integer");
scanf("%i", &num);
number[x] = num;
if (number[x] < min)
min = number[x];
}
int i;
for (i = 0; i < n; i++) {
if (min = number[i])
count++;
}
printf("%s%i", "\nThe smallest Integer you entered was ", min);
printf("%s%i", "\nNumber of times you entered this Integer: ", count);
return 0;
}
But the problem is that when I run this,and I add the integers,it doesnt find the smallest value and how time its repeated correctly!
Where am I wrong?
Assuming your compiler has support for variable length arrays, you need to re-order the calls
int number[n];
scanf("%i", &n);
so that you know the value for n before declaring the array
scanf("%i", &n);
int number[n];
After that, you should initialise min to a larger value to avoid ignoring all positive values
int min = INT_MAX;
(You'll need to include <limits.h> for the definition of INT_MAX)
Finally,
if (min = number[i])
assigns number[i] to min. Use == to test for equality.
Your compiler should have warned you about "assignment in conditional statement" for this last point. If it didn't, make sure you have enabled warnings (-Wall with gcc, /W4 with MSVC)
you are checking array element <0 in line:
if (number[x] < min/*as u specified min =0 before*/),...
so the minimum is set to be zero and there is no replacement actually happening..
The full solution:
#include <stdio.h>
int main() {
int n = 1, min = 0, count = 0;
int number[n];
printf("Enter the size of array you want");
scanf("%i", &n);
int x,y;
for (y = 0; y < n; y++)
{
printf("\nEnter a Integer");
scanf("%i", &number[y]);
}
min=number[0];
for (x = 0; x < n; x++) {
if (number[x] < min)
min = number[x];
}
int i;
for (i = 0; i < n; i++) {
if (min == number[i])
count++;
}
printf("%s%i", "\nThe smallest Integer you entered was ", min);
printf("%s%i", "\nNumber of times you entered this Integer: ", count);
return 0;
}
for (i = 0; i < n; i++) {
if (min = number[i])
count++;
}
Replace min = number[i] with min == number[i].
1.Only After the user input the array size, then you can determine the size of the array number.As the size of the array are uncertain, you should use malloc to allocate the array dynamically.
2.you should set min to the first element of the array. As the min of user input may be great than zero, if you set min to zero, then it will return zero even though the minimum is great than zero
3.you should use == but not = to test the equality of two numbers.
4.last, you should use free to make the memory available and avoid memory leak.
Below is the full program:
#include <stdio.h>
int main() {
int n = 1, min = 0, count = 0;
int* number;
printf("Enter the size of array you want");
scanf("%i", &n);
number = (int*)malloc(sizeof(int)*n);
int x;
for (x = 0; x < n; x++) {
int num;
printf("\nEnter a Integer");
scanf("%i", &num);
number[x] = num;
if( x == 0 || number[x] < min )
min = number[x];
}
int i;
for (i = 0; i < n; i++) {
if (min == number[i])
count++;
}
printf("%s%i", "\nThe smallest Integer you entered was ", min);
printf("%s%i", "\nNumber of times you entered this Integer: ", count);
free(number);
number = NULL;
return 0;
}
In your code
if (min = number[i])
you assigned number[i] to min. You should write
if (min == number[i])
instead.
There are couple of things wrong on your code. First you defined array number[1]. Secondly min in initialised to min = 0.
I suggest defined the array for a maximum possible size, like number[100]. And read the numbe of inputs n from the user, and only use the first n elements of the array. For the second issue, define min as the maximum number represented by int type.

Resources