Using C to Find Min and Max value using Function - c

I need to write a program where users can input their numbers as much as many as they defined, then the program will try to find which one is the lowest value and the highest value. The problems I face are:
When the program executed, the second line will wait on user's input (number) before the printf
The error "system" seems unreliable, sometimes works, sometimes doesn't work
The program only checks the last number entry, therefore it only shows the last number in min and max
You may give hints or corrections along the answers. Thank you very much.
#include <stdio.h>
float max(float num1){
float a=0, b;
if(num1 > a){
a=num1;
}
return a;
}
float min(float num2){
float x=100, y;
if(num2 < x ){
x=num2;
}
return num2;
}
int main(){
int times, interval;
float mini, maxi, data_Input;
printf("How many number would you like to type in ? : ");
scanf("%d\n",&times);
printf("Type in the number: ");
scanf("%f", &data_Input);
for(interval=2; interval<=times; interval++){
printf("\nType in the number: ");
scanf("%f",&data_Input);
while(data_Input<0){
printf("Invalid Input! Please re-enter the number:");
scanf("%f",&data_Input);
}
while(data_Input>100){
printf("Invalid Input! Please re-enter the number:");
scanf("%f",&data_Input);
}
}
maxi= max(data_Input);
mini= min(data_Input);
printf("The Lowest Number is %.2f\n", mini);
printf("The Highest Number is %.2f\n", maxi);
return 0;
}
Output:
How many number would you like to type in? : 5
70
Type in the number :
Type in the number : 90.7
Type in the number : 99
Type in the number : 30
Type in the number : 50
The Lowest Number is 50.00
The Highest Number is 50.00

Okay, the thing is that you are not updating the data_input after every successive number is inputted. What you are doing is, comparing the last number to 0 or 100, which is logically incorrect.
How about you take the first number as input, then after every successive input, compare it with the min and max value. Here is the sample code.
#include <stdio.h>
float max(float num1, float num2){
if(num1 > num2){
return num1;
}
return num2;
}
float min(float num1, float num2){
if(num1 < num2){
return num1;
}
return num2;
}
int main(){
int times, interval;
float mini, maxi, data_Input;
printf("How many number would you like to type in ? : ");
scanf("%d\n",&times);
printf("Type in the number: ");
scanf("%f", &data_Input);
// the first number will be minimum and maximum
mini = data_Input;
maxi = data_Input;
for(interval=2; interval<=times; interval++){
printf("\nType in the number: ");
scanf("%f",&data_Input);
// make it a composite if condition
while(data_Input<0 || data_Input>100){
printf("Invalid Input! Please re-enter the number:");
scanf("%f",&data_Input);
}
maxi= max(maxi, data_Input);
mini= min(mini, data_Input);
}
printf("The Lowest Number is %.2f\n", mini);
printf("The Highest Number is %.2f\n", maxi);
return 0;
}

The program checks the last number because you are calling the min and max function out of the for bracelets so instead you can call them inside the for bracelets like:
for(interval=2; interval<=times; interval++){
printf("\nType in the number: ");
scanf("%f",&data_Input);
while(data_Input<0){
printf("Invalid Input! Please re-enter the number:");
scanf("%f",&data_Input);
}
while(data_Input>100){
printf("Invalid Input! Please re-enter the number:");
scanf("%f",&data_Input);
}
maxi= max(data_Input);
mini= min(data_Input);
}
and instead of rewriting the same code you can just ask for the numbers inside the for loop and to initialize your interval to 1 so your main will look like:
int main(){
int times, interval;
float mini, maxi, data_Input;
printf("How many number would you like to type in ? : ");
scanf("%d\n",&times);
for(interval=1; interval<=times; interval++){
printf("\nType in the number: ");
scanf("%f",&data_Input);
while(data_Input<0){
printf("Invalid Input! Please re-enter the number:");
scanf("%f",&data_Input);
}
while(data_Input>100){
printf("Invalid Input! Please re-enter the number:");
scanf("%f",&data_Input);
}
maxi= max(data_Input);
mini= min(data_Input);
}
printf("The Lowest Number is %.2f\n", mini);
printf("The Highest Number is %.2f\n", maxi);
return 0;
}

Solving the printf issue is easy. As stdout is line buffered (at least by default - it can be changed) it is flushed whenever a newline is inserted in the buffer. So, just add a newline after each message print, for example
printf("How many number would you like to type in ? : \n");
and you'll be fine.
Talking about the wrong calculation of min and max, your attempt has basically two big issues:
You are not acquiring times inputs, but only one. In fact, every time you call scanf you overwrite the same variable data_Input without performing any comparison with the previous inputs
You call min() and max() function only once, after the last input. Furthermore you try to compare the argument with a local variable that has local storage and a lifetime limited to the function itself so that at the next call it will be initialized again
In order to have a variable inside a function that it is initialized only the first time you can use static keyword. But it is not I suggest you to solve the issue.
In my opinion you don't need comparison functions: you can just update maxi and mini each time you get a new input (solving both the aforementioned issues at once):
int main(){
int times, interval;
float mini, maxi, data_Input;
printf("How many number would you like to type in ? : \n");
scanf("%d",&times);
printf("Type in the number: ");
scanf("%f", &data_Input);
maxi = data_Input;
mini = data_Input;
for(interval=2; interval<=times; interval++){
printf("\nType in the number: \n");
scanf("%f",&data_Input);
while(data_Input<0){
printf("Invalid Input! Please re-enter the number:\n");
scanf("%f",&data_Input);
}
while(data_Input>100){
printf("Invalid Input! Please re-enter the number:\n");
scanf("%f",&data_Input);
}
/* Check input and, in case, update max and min */
if(data_Input > maxi)
maxi = data_Input;
if(data_Input < mini)
mini = data_Input;
}
printf("The Lowest Number is %.2f\n", mini);
printf("The Highest Number is %.2f\n", maxi);
return 0;
}
The comparison is performed inside the loop, so you don't need to store the inputs into an array.

You have plenty issues in your code.
Functions min & max do not make any sense
You do not check result of the scanf and you do not know if it was successfull
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define MIN(a, b) ((a) < (b) ? (a) : (b))
int main()
{
int times, interval;
float mini, maxi, data_Input;
do
{
printf("\nHow many number would you like to type in ? : ");
}while(scanf(" %d\n",&times) != 1);
for(interval = 0; interval < times; interval++)
{
do
{
printf("\nType in the number: ");
}while(scanf(" %f",&data_Input) != 1 && (data_Input < 0 || data_Input > 100));
printf("%f\n", data_Input);
maxi = interval == 0 ? data_Input : MAX(maxi, data_Input);
mini = interval == 0 ? data_Input : MIN(mini, data_Input);
}
printf("The Lowest Number is %.2f\n", mini);
printf("The Highest Number is %.2f\n", maxi);
return 0;
}

When the program executed, the second line will wait on user's input (number) before the printf
Drop "\n" from "%d\n". It blocks until non-white space detected after the number and is not needed.
printf("How many number would you like to type in ? : ");
// scanf("%d\n",&times);
scanf("%d",&times);
printf("Type in the number: ");
If output still not seen when expected, flush it. Typically printing a '\n' will flush stdout, but not certainly.
printf("How many number would you like to type in ? : ");
fflush(stdout); // add
The error "system" seems unreliable, sometimes works, sometimes doesn't work
At least this issue: sequential check vs. checking both conditions together input validity.
Rather than
while(data_Input<0){
...
}
while(data_Input>100){
...
}
Test together.
while(data_Input<0 || data_Input>100){
...
}
The program only checks the last number entry, therefore it only shows the last number in min and max
True as code only compares values once with one call to max(). That function only compares the number to 0 rather than prior values. Likewise for min().
Consider an algorithm change
// Pseudo code for max
prompt How many number would you like to type in ? : "
get times
max_value = -INF // set to minimum possible float
for each value 1 to times
prompt "Type in the number: "
get data_Input
if data_Input > max_value
max_value = data_Input
print max_value

Related

Program is not printing completely

I'm trying programming 1st time and not getting the output of this program.Though it looks simple but the code doesn't prints after taking the input like name, roll, marks obtained by student.
I have attached the screenshot of compiler.
Thank you!
#include<stdio.h>
int main()
{
int roll,phy,che,ca,total;
float percentage;
char name[20];
printf("enter the name of student: "); //studentname
scanf("%s",&name);
printf("enter the roll number: "); //roll number
scanf("%d",&roll);
printf("enter the marks obtained in phy,che,ca: "); //marks obtained/subject
scanf("%d%d%d ",&phy,&che,&ca);
//doesnt works from here.
total= (phy+che+ca); //calculating total marks
printf("the total marks obtained is %d\n",total);
percentage =total/3.0; //calculating percentage student got.
printf("the total percentage obtained is %d\n",percentage);
if(percentage>=80)
printf("first division\n"); //first division
else if(percentage>=60 && percentage<=80)
printf("second division\n"); //second division
else if(percentage>=60)
printf("third divison\n"); //third division
else if(percentage>=10)
printf("you failed!\n"); //failed
else
printf("invalid input\n"); //invalid input
return 0;
}
screenshot of the compiler
scanf("%d%d%d ",&phy,&che,&ca);
There is an extra blank character in format. So you should input a more character after you input 3 integers.
And you shouldn't use %d to print a float type variable, you should use %f.

I am getting a nan error when doing loops

So, I am using xcode on mac and made a program that basically does simple math with the users entered values and keeps looping unless it is interrupted. At the end of the loop (once it is broken) I want to print out the total average value (so do some more math). I use a counter and sum variables to do this. However, in out output, I am getting a "nan" error when the loop end and the overall average has to display. Can anyone help, please? :/
int main() {
double gallons=0;
double miles=0;
double sum=0;
int count=0;
while (gallons>=0) {
sum+=(miles/gallons);
count++;
printf("\nEnter the gallons used (-1 to end): ");
scanf("%lf",&gallons);
if (gallons<0)
break;
printf("Enter the miles driven: ");
scanf("%lf",&miles);
if (miles<0)
break;
printf("The miles/gallon for this tank was: %lf", miles/gallons);
}
if (gallons<0) {
printf("The average is: %lf", sum/(count-1));
}
return 0;
}
double gallons=0;
double miles=0;
…
sum+=(miles/gallons);
Dividing zero by zero produces a NaN. Once there is a NaN, any arithmetic with it also produces a NaN.
Hm. In first iteration in sum+=(miles/gallons); you try to add to sum value 0/0. So, I think that you need to move this addition after inputs. Something like
printf("\nEnter the gallons used (-1 to end): ");
scanf("%lf",&gallons);
if (gallons<0)
break;
printf("Enter the miles driven: ");
scanf("%lf",&miles);
if (miles<0)
break;
printf("The miles/gallon for this tank was: %lf", miles/gallons);
sum+=(miles/gallons);
count++;

Simple calculator using switch with if else in C

This is my code so far for my simple calculator. Im working on sine right now(case 6) with a degree range of 0-360.Here is the output.
$ ./a.exe ProblemSolving.c
Arithmetic : Add(0) Sub(1) Mult(2) Div(4) Mod(5)
Trigonometry : sine(6) cosine(7) tan(8) arc_sin(9) arc_cos(10)
Exponent : x^y(11) 2^x(12) 10^x(13)
Enter the choice of operation:6
The choice of operation is:6
Enter degree range from 0 to 360
Enter degrees:400
After I enter the desired degrees nothing else happens and the program ends. I believe there is something wrong with my if statement or the sine function.
#include <stdio.h>
#include <math.h>
int main() {
double Add1, Add2, Sub1, Sub2, Mult1, Mult2;
int Choice, Div1, Div2, Mod1, Mod2, Base1, Power1, Deg1;
printf("Arithmetic : Add(0) Sub(1) Mult(2) Div(4) Mod(5)\n");
printf("Trigonometry : sine(6) cosine(7) tan(8) arc_sin(9) arc_cos(10)\n");
printf("Exponent : x^y(11) 2^x(12) 10^x(13)\n");
printf("Enter the choice of operation:");
scanf("%d", &Choice);
printf("The choice of operation is:%d\n", Choice);
switch(Choice) {
case 0:
printf("Enter number one:");
scanf("%lf", &Add1);
printf("Enter number two:");
scanf("%lf", &Add2);
printf("%2.2lf + %2.2lf = %2.2lf", Add1, Add2, Add1+Add2);
break;
case 1:
printf("Enter number one:");
scanf("%lf", &Sub1);
printf("Enter number two:");
scanf("%lf", &Sub2);
printf("%2.2lf - %2.2lf = %2.2lf", Sub1, Sub2, Sub1-Sub2);
break;
case 2:
printf("Enter number one:");
scanf("%lf", &Mult1);
printf("Enter number two:");
scanf("%lf", &Mult2);
printf("%2.2lf * %2.2lf = %2.2lf", Mult1, Mult2, Mult1*Mult2);
break;
case 4:
printf("Enter number one:");
scanf("%d", &Div1);
printf("Enter number two:");
scanf("%d", &Div2);
if (Div2 == 0)
printf("Error! Denominator cannot equal 0");
else
printf("%d / %d = %d", Div1, Div2, Div1/Div2);
break;
case 5:
printf("Enter number one:");
scanf("%d", Mod1);
printf("Enter number two:");
scanf("%d", Mod2);
if (Mod2 == 0)
printf("Error! Denominator cannot equal 0");
else
printf("%d % %d = %d", Mod1, Mod2, Mod1%Mod2);
break;
case 6:
printf("Enter degree range from 0 to 360\n");
printf("Enter degrees:");
scanf("%d", Deg1);
if (0 > Deg1 > 360)
printf("Error! Value Entered is not within valid range");
else
printf("sin(%d) = %d", Deg1, sin(Deg1));
break;
default:
printf("Error! operator is not correct");
break;
}
return 0;
}
There are several problems in this code:
Change scanf("%d", Deg1); to scanf("%d", &Deg1);, because scanf() call for addresses. Also, I think it might be better to declare Deg1 as a double.
0 > Deg1 > 360 is wrong in C. You have to write Deg1 < 0 || Deg1 > 360. Operator || stands for "logical Or".
In math.h, sin() works in radians. So use sin(Deg1 * 3.14159265 / 180). Or, to improve readability and maintenance, #define PI 3.14159265 and sin(Deg1 * PI / 180). Note that you cannot write Deg1 / 180 * 3.14159265, because integer literals in C is ints, and int/int = int. For example, 3 / 2 == 1, rather than 1.5. To get the exact value, write 3.0 / 2.0.
In math.h, sin() returns double, so write printf("sin(%d) = %g", Deg1, sin(...));.
Fixed code here:
#include <stdio.h>
#include <math.h>
#define PI 3.14159265
// ...many lines of code...
case 6:
printf("Enter degree range from 0 to 360\n");
printf("Enter degrees:");
scanf("%d", &Deg1);
if (0 > Deg1 || Deg1 > 360)
printf("Error! Value Entered is not within valid range");
else
printf("sin(%d) = %g", Deg1, sin(Deg1 * PI / 180));
break;
The sine function (and the rest of the trig functions) in C works in radians, not degrees. You'll have to convert from degrees from radians before passing the value to sine.
Right now you also have a problem with the format in your printf, since you're passing a double, but telling printf to expect an int. You need to use %f instead of %d.
In addition, your if statement doesn't currently make much sense, and almost certainly doesn't mean what you think. What you apparently want is if (Deg1 < 0.0 || Deg1 > 360.0)

How to create a loop without knowing when the loop will stop?

I am trying to create a program which takes a number and we match that number with a variable which has a specific number stored. We need to keep doing that until the user enters the correct number that matches the number we have stored in our variable:
#include <stdio.h>
int main(void) {
int i;
int j;
int num1;
int num2 = 2;
printf("Enter number");
scanf("%d", &num1);
while (num1 == 0) {
printf("Enter number");
scanf("%d", &num1);
}
while (num1 != num2) {
for(j=1;j
printf("This is not the correct number! \n");
printf("Enter number again: ");
scanf("%d", &num1);
}
if (num1 == num2) {
printf("The numbers have matched! \n");
}
}
I am confused with how do we create a loop where we don't know how many times the user will enter an incorrect number. What I want with the loop is to display
is how many times the user enters an incorrect number. Let say if they enter 3 times.
This is not the correct number 1!
This is not the correct number 2!
This is not the correct number 3!
But we don't know how many times the user will enter an incorrect number, so what condition do I put in a loop, so it counts.
You want to create a separate counter variable that keeps track of how many times you've gone through the loop. Set it to 0 before the loop, then increment on each iteration.
int count = 0;
...
while (num1 != num2) {
count++;
printf("This is not the correct number %d! \n", count);
printf("Enter number again: ");
scanf("%d", &num1);
}
Also, I'm presuming this is a typo:
for(j=1;j

C program gives incorrect output?

I am writing a C program which calculates average grade and tells if you pass or fail. The user can choose as many attempts as they want and they will be given a final average of all attempts. Here is my code:
#include <stdio.h>
int main(void)
{
int num1;
double num2, num3, average, average_1;
printf("Enter number of attempts: ");
scanf("%d", &num1);
while (num1 > 0) {
printf("Enter your mark for subject one: ");
scanf("%lf", &num2);
printf("Enter your mark for subject two: ");
scanf("%lf", &num3);
if (num2 < 50 || num3 < 50) {
printf("You have failed \n");
} else {
printf("You have passed \n");
}
num1--;
}
average = num1 * num2 * num3;
average_1 = average / 100;
printf("Average for all %d attempts is %.2f \n", num1, average_1);
}
The problem with this code is that the final output, which is the last printf line, gives me 0 for attempts and 0 for average. Here is the exact output:
Enter number of attempts: 2
Enter your mark for subject one: 49
Enter your mark for subject two: 96
You have failed
Enter your mark for subject one: 22
Enter your mark for subject two: 100
You have failed
Average for all 0 attempts is 0.00
You are dicrementing the variable num1. So, when you finish your loop you will have num1 = 0.
I suggest you do a 'for' instead of a 'while'. Like this:
#include <stdio.h>
int main(void) {
int num1, i;
double num2,num3,average,average_1;
printf("Enter number of attempts: ");
scanf("%d", &num1);
for(i = num1; i > 0; i--) {
printf("Enter your mark for subject one: ");
scanf("%lf", &num2);
printf("Enter your mark for subject two: ");
scanf("%lf", &num3);
if (num2 < 50 || num3 < 50) {
printf("You have failed \n");
}
else {
printf("You have passed \n");
}
}
average = num1*num2*num3;
average_1 = average / 100;
printf("Average for all %d attempts is %.2f \n", num1, average_1);
}
You have put the average calculation part in wrong place. Once you're out of the while loop, num1 will have a value 0, hence all the related calculations will return 0.
You are reducing num1 until it becomes 0
while (num1 > 0) {
// other code
num1--;
}
Then naturally
average = num1*num2*num3;
becomes
average = 0*num2*num3;
and that is 0
First, because you deduct num1 by one till 0.
You should use for loop:
for(int counter = num1; num1 > 0; num--)
{ Your code here }
Your loop will iterate until num1 is greater than 0 . As it decrement and become 0 program come out of loop but num1 has value 0 . Thus ,in these expressions num1 is 0-
average = num1*num2*num3; // 0*num2*num3 therefore , 0
average_1 = average / 100; // as average is 0 , thus result is 0
Also formula for calculating average_1 is wrong . It should be -
average_1=average/3; // you calculate average of 3 numbers
To get correct output create a temporary variable -
int i=num1;
while(i>0){
// your code
i--;
}
In this way num1 remain unchanged.
after the while loop, your num1 will be 0.

Resources