C Program: Updating max and min integers without using arrays - c

I'm experimenting with a simple C program that should prompt user to enter a chosen number of positive integers. I'm having an issue getting the maximum and minimum of the set of integers I input without the use of an array.
The way that I currently have it is that it will update the max and min among the last two entered values. If someone wouldn't mind looking to see what I'm doing wrong, it would be appreciated.
take a look here:
#include<stdio.h>
int main()
{
int N ,i, value=0, min=0, max=0, sum=0, oldmin=0, Newmin=0, oldmax=0, Newmax=0;
double mean;
do{
printf("How many values are to be entered?: ");
scanf("%d", &N);
printf("\n");
if (N>0){
do{
if (N>0){
// 1st value updated
for (i=1;i<=N;i++)
{
printf("Value %d:\n",i);
scanf("%d", &value);
sum = sum+value;
}
mean = (double)sum/(double)N;
//max
if(oldmax<Newmax){
max = Newmax;
}
else max = oldmax;
//min
if(oldmin>Newmin){
min = Newmin;
}
else min = oldmin;
}
else printf("INPUT ERROR!\n");
}
while(N<0);
printf("\nThe minimum value is %d, the maximum value is %d, and the average value is %.2lf.",min,max,mean);
}else printf("INPUT ERROR!\n");
} while(N<0);
return 0;}

some remarks :
you need to set the min/max value from value in the same loop you do sum = sum+value; , this is the reason of your problem about min/max
check the scanf result to be sure a number was enter
if (N>0){ do{ if (N>0){ so two check but N never change
if (N > 0) { do { ... } while (N<0); } that has no sense
the embedded loops have no sense, only 1 loop is needed
A proposal removing the problems :
#include<stdio.h>
int main()
{
int N;
fprintf(stderr, "How many values are to be entered?: ");
if ((scanf("%d", &N) != 1) || (N <= 0))
printf("INPUT ERROR!\n");
else {
int i, min, max, sum = 0;
for (i = 0; i < N; ++i) {
int value;
fprintf(stderr, "Value %d:\n",i);
if (scanf("%d", &value) != 1) {
printf("INPUT ERROR!\n");
return -1;
}
sum = sum+value;
if (i == 0) {
min = max = value;
}
else {
if (value < min)
min = value;
if (value > max)
max = value;
}
}
printf("\nThe minimum value is %d, the maximum value is %d, and the average value is %.2lf\n",
min,max, (double)sum/(double)N);
}
return 0;
}
Compilation and execution :
pi#raspberrypi:/tmp $ gcc -g -pedantic -Wextra c.c
pi#raspberrypi:/tmp $ ./a.out
How many values are to be entered?: 3
Value 0:
1
Value 1:
2
Value 2:
3
The minimum value is 1, the maximum value is 3, and the average value is 2.00
I used fprintf to flush the message with a \n, and I set the first min and max value on the first turn to not have to use the MIN_INT MAX_INT may be not defined for you

if(oldmax<Newmax){
Don't compare newmax and oldmax. Compare max and value. Same with min.
I'm not even sure about the purpose of Newmax and oldmax. Remove these variables all-together, as it will just confuse you.
Just use min, max, and value. It will sort out.

Related

Sorting array elements to find the largest and smallest number in C

I'm solving this problem where I need to give some inputs, find the largest and smallest among them. Here is the problem statement
Ivan Vasilyevich came to the market and decided to buy two watermelons: one for himself and another for the wife's mother. It is clear to choose for himself the heaviest watermelon, and for mother-in-law the lightest. But there is one problem: there are many watermelons and he does not know how to choose the lightest and the heaviest one. Help him!
Input
The first line contains the number of watermelons n (n ≤ 30000). The second line contains n numbers, each number is a mass of corresponding watermelon. All weights of watermelons are positive integers and do not exceed 30000.
Output
Print two numbers: the weight of watermelon that Ivan Vasilyevich will buy for his mother-in-law and the weight of watermelon that he will buy himself, or print the message "Ooops!" (without quotes), if someone left without watermelon
Here's my code
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i, w[30000], gw, lw;
scanf("%d", &n);
n = abs(n);
for (i = 0; i < n; i++)
{
scanf("%d", &w[i]);
}
if (n >= 2)
{
for (i = 0; i < n; i++)
{
if (w[0] < w[i])
w[0] = w[i];
gw = w[0];
}
for (i = 0; i < n; i++)
{
if (w[0] > w[i])
w[0] = w[i];
lw = w[0];
}
printf("%d %d", lw, gw);
return 0;
}
else
{
printf("Ooops!");
return 0;
}
}
I'm getting wrong answer(96/100). What am I getting wrong?
You do not need to allocate space for an array of 30k integers to find the min and max weights entered.
First, initialize min and max weights to the first integer entered and then update min and max accordingly as you read more weights. Use the variable cur (an integer) to store the last integer (i.e. weight) read.
That way, you do it all in one pass, rather than in multiple loops.
If you use scanf, it is good practice to check it's return value. For reference (from the C99 standard):
The scanf function returns the value of the macro EOF if an input failure occurs before any conversion. Otherwise, the scanf function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure.
In our case, when our scanf call is of the form scanf("%d", &a) where a is some int, we expect the call scanf("%d", &a) to return 1.
While it is good practice to check the return value, it is not absolutely necessary. If this is a program for one of your classes and you have never worked with the return value of scanf, you could remove all the checks for the return value below and the program should function the same. That said, it would show great initiative if you do check for the return value and reference the C standard in your justification for checking it (as the return value provides very useful information).
#include <stdio.h>
#include <stdlib.h>
#define MAX_WAT 30000 /* maximum number of watermelons */
int main(void) {
int n, i, min, max, cur;
/* prompt user for number of watermelons */
printf("Enter number of watermelons: ");
/* read integer, checking return value of scanf as expected */
if (scanf("%d", &n) != 1) {
printf("error in scanf\n");
exit(EXIT_FAILURE);
}
if (n > MAX_WAT) {
printf("Please enter less than %d watermelons.\n", MAX_WAT);
return 0;
}
/* if zero or one watermelons, at least one person leaves without */
if (n <= 1) {
printf("Ooops!\n");
return 0;
}
/* initialize min, max to first integer and update
min, max accordingly as new weights are read */
printf("Enter weights of %d watermelons: ", n);
scanf("%d", &cur);
min = max = cur;
for (i = 1; i < n; i++) {
if (scanf("%d", &cur) != 1) {
printf("error in scanf\n");
exit(EXIT_FAILURE);
}
if (cur < min)
min = cur;
if (cur > max)
max = cur;
}
printf("Ivan Vasilyevich: %d\nMother: %d\n", max, min);
return 0;
}
Example Session 1:
Enter number of watermelons: 5
Enter weights of 5 watermelons: 2 5 1 9 10
Ivan Vasilyevich: 10
Mother: 1
Example Session 2:
Enter number of watermelons: 1
Ooops!
Example Session 3:
Enter number of watermelons: 30001
Please enter less than 30000 watermelons.
do not modify your original array
initialize your gw and lw
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i, w[30000], gw, lw;
scanf("%d", &n);
n = abs(n);
for (i = 0; i < n; i++)
{
scanf("%d", &w[i]);
}
if (n >= 2)
{
gw = w[0];
for (i = 0; i < n; i++)
{
if (gw < w[i]) gw = w[i];
}
lw = w[0];
for (i = 0; i < n; i++)
{
if (lw > w[i]) lw = w[i];
}
printf("%d %d", lw, gw);
return 0;
}
else
{
printf("Ooops!");
return 0;
}
}

For loop inside function does'n seem to work properly in C

I have to create a function in c that one value and two pointers, verify if the value is a prime number or if it is a composite number, show the maximum and minimum divisors and return 1 for composite and 0 for prime. The problem is the minimum value is returned correctly but the maximum value returns something out of for loop restriction, for example:
n = 12
min is 2 max is 61
Why *max = i is returning a number bigger than the variable "value"?
Here is the code:
#include<stdio.h>
int divs(int value, int *max, int *min)
{
for (int i = 2; i < value; i++)
{
if (value % i == 0){
if (*max == 0){
*min = i;
}
*max = i;
}
}
if (*max != 0)
return 1;
else
return 0;
}
int main(void)
{
int n,max = 0,min = 0,result;
printf("type a number bigger than 2\n");
scanf("%d",&n);
divs(n,&max, &min);
result = divs(n,&max, &min);
if (result == 1)
printf("min is: %d max is: %d",min,max);
printf("%d\n",result);
return 0;
}
Your code is fine, you just left out a \n in your printf statement in main, change to this:
printf("min is: %d max is: %d\n",min,max);
Which caused your next printf ('1') to print right next to it.
You did not print a new line:
if (result == 1)
printf("min is: %d max is: %d",min,max);
printf("%d\n",result);
When result is 1, you first print min is: 2 max is: 6, and then you print 1.
Change the first part to:
if (result == 1)
printf("min is: %d max is: %d\n", min, max);

C Program that prints out the maximum and minimum values from user input involving precision decimals

I am a newbie programmer and just started to teach myself C then decided to tackle some simple problems taken from the internet. Specifically with this one:
Problem
And my solution is:
#include <stdio.h>
#include <math.h>
#include <float.h>
#include <limits.h>
int main() {
double min = DBL_MAX;
double max = DBL_MIN;
double n;
do {
scanf("%lf", &n);
if (n < 0.0001) {
break;
}
if (n > max) {
max = n;
}
if (n < min) {
min = n;
}
} while (n > 0.0000);
printf("Min: %.4f Max: %.4f\n", min, max);
return 0;
}
However, I need to run my program exactly as the input/output specified by the problem.
For example, consider I am inputting in different lines:
1.1 1.2 1.3 3 6 9 11 -2 7
2.2
2.3 12
0
The program should output 12 as the max and -2 as the min, the program ends when the 0 was inputted.
You need to set min and max BOTH to the first value set by scanf and then check for greater and less than on later iterations. The way it works now, min starts at 0 and will never change as nothing can be lower than that without the program exiting.
int main(){
double min = 0;
double max = 0;
float n;
int count = 0;
do{
scanf("%f", &n);
if(n < 0.0001){
break;
}
if( count ) {
if(n > max){
max = n;
} else if(n < min){
min = n;
}
} else {
max = n;
min = n;
count = 1;
}
}while(n > 0);
printf("Min: %.4f Max: %.4f\n", min, max);
return 0;
}
Also, the proper type for float is %f.
Make sure you read the problem description again, your logic in the code is tainted in comparison to what's being attempted.
According to the problem description, n can be an int as you're using it to define the number of values to be given to the program.
You can then use a for loop (for(i=0; i < n; i++){CODE HERE}) to gather more input from the user. The first number given should be your base value for the min and max values.
After you have a base value you can compare min and max to each input thereafter. (ie. if(max < input) {max = input} and if(min > input) {min = input})
If you have anymore questions feel free to inbox me and I'll try to help you work out the problem :)
Using math.h you can use INFINITY and -INFINITY.
http://pubs.opengroup.org/onlinepubs/007904975/basedefs/math.h.html
Comparing doubles with literals in order to make decisions is tricky at best. Besides it would be better to have positive as well as negative numbers in your program.
fflush(stdin) gets rid of any previous input in the buffer.
Notice that max starts at -INFINITY and min starts at +INFINITY.
Comparing a float with a double will result in the calculation being performed using the double type anyways. Try not to mix these without a good reason.
#include <stdio.h>
#include <math.h>
int main()
{
double min = +INFINITY;
double max = -INFINITY;
double n;
char ans = 'n';
do
{
printf("Enter a number: ");
scanf("%lf", &n);
if(n > max)
{
max = n;
}
if(n < min)
{
min = n;
}
fflush(stdin); // gets rid of previous input
printf("Another number? (y/n): ");
scanf("%c", &ans);
}
while(ans == 'y');
printf("Min: %.4f Max: %.4f\n", min, max);
return 0;
}
Output:
Enter a number: -45.6
Another number? (y/n): y
Enter a number: 23.0
Another number? (y/n): y
Enter a number: 92.3
Another number? (y/n): y
Enter a number: -100.22
Another number? (y/n): n
Min: -100.2200 Max: 92.3000
Process returned 0 (0x0) execution time : 15.805 s
Press any key to continue.

Receiving non-zero exit status when filling an array dynamically from user input

#include <stdio.h>
int main(void){
int inputNumber;
int counter=0;
int totalValue;
int arr[counter];
int avg;
puts("Please enter any number of positive whole numbers you would like to be averaged. Enter ' -1 ' when you are finished for your result.\n");
while(scanf("%d\n", &arr[counter])){
if(arr[counter] = -1){
break;
}
if(arr[counter] > 0){
totalValue += arr[counter];
++counter;
}
else if(arr[counter]<=0){
puts("Please enter a positive number.");
}
else{
}
}
avg = totalValue/counter;
printf("The average of your entered values is: %d", avg);
return 0;
}
I have attempted many things to try and stop it, and although this may come from a lack of knowledge is there really any way to do this other than creating an enormously large array?
I tried using a dynamic array with calloc() but i was met with the same errors. I am unsure what else is available as an option in this method.
The code is supposed to take the average of "n" user inputted values.
You do not need an array.
Quick & dirty but easier that you wanted to do
int number = 0;
int counter = 0;
int total = 0;
while (number != -1)
{
total += number;
++counter;
scanf("%d", &number);
}
printf("average = %d\n", total / (counter - 1) );

Writing a program to find the largest in a series of numbers.

I am very new to C. I am using A modern Approach to C programming by King 2nd Edition.
I am stuck on chapter 6. Question 1: Write a program that finds the largest in a series of numbers entered by the user. The program must prompt the user to enter the numbers one by one. When the user enters 0 or a negative number, the program must display the largest non negative number entered.
So far I have:
#include <stdio.h>
int main(void)
{
float a, max, b;
for (a == max; a != 0; a++) {
printf("Enter number:");
scanf("%f", &a);
}
printf("Largest non negative number: %f", max);
return 0;
}
I do not understand the last part of the question, which is how to see which non-negative number is the greatest at the end of user input of the loop.
max = a > a ???
Thanks for your help!
So you want to update max if a is greater than it each iteration thru the loop, like so:
#include <stdio.h>
int main(void)
{
float max = 0, a;
do{
printf("Enter number:");
/* the space in front of the %f causes scanf to skip
* any whitespace. We check the return value to see
* whether something was *actually* read before we
* continue.
*/
if(scanf(" %f", &a) == 1) {
if(a > max){
max = a;
}
}
/* We could have combined the two if's above like this */
/* if((scanf(" %f", &a) == 1) && (a > max)) {
* max = a;
* }
*/
}
while(a > 0);
printf("Largest non negative number: %f", max);
return 0;
}
Then you simply print max at the end.
A do while loop is a better choice here because it needs to run at least once.
#include<stdio.h>
int main()
{
float enter_num,proc=0;
for(;;)
{
printf("Enter the number:");
scanf("%f",&enter_num);
if(enter_num == 0)
{
break;
}
if(enter_num < 0)
{
proc>enter_num;
proc=enter_num;
}
if(proc < enter_num)
{
proc = enter_num;
}
}
printf("Largest number from the above is:%.1f",proc);
return 0;
}

Resources