if else statement not giving expected answer - c

The values entered are not matching with the output grade as it is giving 10 grade even when the conditions for 10 are not met.
the issue is that on entering hardness 50 strength 5600 and carbon 0.7 its giving grade 10 while for grade 10 carbon should be less than 0.7?
#include
#include
#include
int main() {
// program grade the steel on quality basis
int hardness;
int strength;
float carbon;
printf("Enter the hardness of steel:"); // condition 1 hardness should be >= 50
scanf("%d", &hardness);
printf("Enter the tensile strength:"); // condition 2 strength should be >= 5600
scanf("%d", &strength);
printf("Enter carbon content:"); // condition 3 carbon less than 0.7
scanf("%.2f", &carbon);
if ((hardness >= 50) && (carbon < 0.7) && (strength >= 5600)) { // all true
printf("\ngrade = 10");
}
else if ((hardness >= 50) && (carbon < 0.7) && (strength <= 5600)) { // 1 and 2 true
printf("\ngrade = 9");
}
else if ((hardness <= 50) && (carbon < 0.7) && (strength >= 5600)) { // 2 and 3 true
printf("\ngrade = 8");
}
else if ((hardness >= 50) && (carbon > 0.7) && (strength >= 5600)) { // 1 and 3 true
printf("\ngrade = 7");
}
else if ((hardness >= 50) && (carbon > 0.7) && (strength <= 5600)) { // any one true
printf("\ngrade = 6");
}
else if ((hardness <= 50) && (carbon < 0.7) && (strength <= 5600)) { // any one true
printf("\ngrade = 6");
}
else if ((hardness <= 50) && (carbon < 0.7) && (strength >= 5600)) { // any one true
printf("\ngrade = 6");
}
else {
printf("\ngrade = 5"); // none true
}
_getch();
return 0;
}

Use of "%.2f" as format specifier is not correct in scanf. It is good for printf but not scanf.
It's a good idea to always check the return value of scanf to make sure that the function was able to read the expected data.
if ( scanf("%.2f", &carbon) != 1 )
{
// Deal with error.
}
Add similar checks to the other scanf calls.
I think changing the above format specifier to "%f" should fix your problem. Add the check still.
if ( scanf("%f", &carbon) != 1 )
{
// Deal with error.
}

The problem is with the format specifier(.2f) in scanf statement.
%.2f is generally used to print 2 digits after the point
In C,all float literals are stored as double precision values.So we need to specify that we are using float i.e single precision by appending the values by f.Check the change of code
if you want your carbon to be rounded of to 2 digit precision, you can use carbon = ceilf(carbon*100)/100.0;
When you post your question next time, post your input for which it fails, you will get quick reply
And you can write this with less number of comparisons- here is the working code
#include<stdio.h>
int main(void) {
int hardness;
int strength;
float carbon;
printf("Enter the hardness of steel:");
scanf("%d", &hardness);
printf("Enter the tensile strength:");
scanf("%d", &strength);
printf("Enter carbon content:");
scanf("%f", &carbon);
if ((hardness >= 50) && (carbon < 0.7f) && (strength >= 5600))
printf("\ngrade = 10");
else if ((hardness >= 50) && (carbon < 0.7f))
printf("\ngrade = 9");
else if ((carbon < 0.7f) && (strength >= 5600))
printf("\ngrade = 8");
else if ((hardness >= 50) && (strength >= 5600))
printf("\ngrade = 7");
else if ((hardness >= 50) || (carbon > 0.7f) || (strength <= 5600))
printf("\ngrade = 6");
else
printf("\ngrade = 5");
_getch();
return 0;
}

Related

Problem checking numbers between 1 and 100

I am trying to write a C program that can accept 10 numbers between 1 and 100. If values outside the range are entered an error message should be displayed.
I have managed to write the following code to check for the to check if the numbers are between 1 to 100
#include <stdio.h>
int main() {
int num1, num2, num3, num4, num5, num6, num7, num8, num9, num10;
printf("\nEnter the first number : ");
scanf("%d", & num1);
printf("\nEnter the second number : ");
scanf("%d", & num2);
printf("\nEnter the third number : ");
scanf("%d", & num3);
printf("\nEnter the fourth number : ");
scanf("%d", & num4);
printf("\nEnter the fifth number : ");
scanf("%d", & num5);
printf("\nEnter the sixth number : ");
scanf("%d", & num6);
printf("\nEnter the seventh number : ");
scanf("%d", & num7);
printf("\nEnter the eighth number : ");
scanf("%d", & num8);
printf("\nEnter the nineth number : ");
scanf("%d", & num9);
printf("\nEnter the tenth number : ");
scanf("%d", & num10);
if ((num1 <= 1 && num2 <= 1 && num3 <= 1 && num4 <= 1 && num5 <= 1 && num6 <= 1 && num7 <= 1 && num8 <= 1 && num9 <= 1 && num10 <= 1) && (num1 >= 100 && num2 >= 100 && num3 >= 100 && num4 >= 100 && num5 >= 100 && num6 >= 100 && num7 >= 100 && num8 >= 100 && num9 >= 100 && num10 >= 100)) {
printf("good");
printf("Numbers are good");
} else {
printf("All numbers must be between 1 to 100");
}
return (0);
}
When i run the code i get this output "All numbers must be between 1 to 100" Even if the numbers i enter are between the range of 1-100. i expect the output to be "Numbers are good". Please help.
Your test is wrong, you want (n >= 1) && (n <= 100) not (n <= 1) && (n >= 100)
Also use a loop to manage all the inputs rather duplicating the code, imagine if you have to enter 1000 numbers.
A proposal:
#include <stdio.h>
#define N 10
int main() {
int isAllOk = 1;
int nums[N]; /* to save the values to have them available later even not used in your question */
for (int i = 0; i != N; ++i) {
printf("\nEnter number %d : ", i + 1);
if (scanf("%d", & nums[i]) != 1) {
fprintf(stderr, "invalid input\n");
return -1;
}
isAllOk &= ((nums[i] >= 1) && (nums[i] <= 100));
}
puts((isAllOk) ? "Numbers are good" : "All numbers must be between 1 to 100");
return (0);
}
Compilation and execution:
pi#raspberrypi:/tmp $ gcc -pedantic -Wall -Wextra l.c
pi#raspberrypi:/tmp $ ./a.out
Enter number 1 : 1
Enter number 2 : 2
Enter number 3 : 44
Enter number 4 : 3
Enter number 5 : 3
Enter number 6 : 3
Enter number 7 : 3
Enter number 8 : 3
Enter number 9 : 3
Enter number 10 : 3
Numbers are good
pi#raspberrypi:/tmp $ ./a.out
Enter number 1 : 111111111
Enter number 2 : 23
Enter number 3 : 3
Enter number 4 : 3
Enter number 5 : 3
Enter number 6 : 3
Enter number 7 : 3
Enter number 8 : 3
Enter number 9 : 3
Enter number 10 : 3
All numbers must be between 1 to 100
Note it is also possible to stop immediately when a number is not between 1 and 100 but that seems not compatible with your request.
The condition in the if statement is wrong. It must be x=>1 and x<=100. And also it doesn't have to separate all scanf and condition.
Your condition is 1<=num<=100, not 1>=num and 100>=num, so the solution would be to change the if condition, like this:
if (
(num1 >= 1 && num2 >= 1 && num3 >= 1 && num4 >= 1 && num5 >= 1 && num6 >= 1 && num7 >= 1 && num8 >= 1 && num9 >= 1 && num10 >= 1) &&
(num1 <= 100 && num2 <= 100 && num3 <= 100 && num4 <= 100 && num5 <= 100 && num6 <= 100 && num7 <= 100 && num8 <= 100 && num9 <= 100 && num10 <= 100)
) {
printf("Numbers are good");
} else {
printf("All numbers must be between 1 to 100");
}
(n <= 1) && (n >= 100) is wrong. It should have been (n >= 1) && (n <= 100). Now you can improve your design with loops, arrays and dedicated functions. This makes your code easier to read/understand and also easily modifiable. Adding another 10 values to the bunch shouldn't mean 10 more (handwritten) checks, and changing the range shouldn't mean changing all 20 checks anew. Here's an example implementation:
#include <stdio.h>
#include <stdbool.h>
bool numb_in_range(int numb, int lower, int upper)
{
return (numb >= lower) && (numb <= upper);
}
bool arry_in_range(int* arry, size_t sz, int lower, int upper)
{
for (size_t i = 0; i != sz; ++i)
{
if (!numb_in_range(arry[i], lower, upper))
{
return false;
}
}
return true;
}
int main(void)
{
const size_t sz = 10;
int arry[sz];
for (size_t i = 0; i != sz; ++i)
{
scanf("%d", arry + i);
}
if (arry_in_range(arry, 10, 1, 100))
{
puts("good");
}
else
{
puts("bad");
}
return 0;
}
You need to revert all comparisons like this:
if ((num1 >= 1 && num2 >= 1 && ... && num10 >= 1) &&
(num1 <= 100 && num2 <= 100 && ... && num10 <= 100))
If N is a number greater than or equal to 1 and less than or equal to 100, we denote it by:
if(N >= 1 && N <= 100)
The problem are the comparators, because the condition is wrong.
You accept as good when numbers are lower than 1 and higher than 100.
if (
(num1 >= 1 && num2 >= 1 && num3 >= 1 && num4 >= 1 && num5 >= 1 && num6 >= 1 && num7 >= 1 && num8 >= 1 && num9 >= 1 && num10 >= 1) &&
(num1 <= 100 && num2 <= 100 && num3 <= 100 && num4 <= 100 && num5 <= 100 && num6 <= 100 && num7 <= 100 && num8 <= 100 && num9 <= 100 && num10 <= 100)
) {
printf("good");
}

comparing an inputted string to a printed function

Below is a code I wrote for a dice game called cho han. To input your guess I've used number to represent the words 'odd' and 'even'. Since then I have tried to write it again, but to actually write odd or even in the scanf section, but can't get it to work. Any help would be appreciated :)
//cho-han
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
srand(time(NULL));
int x = (rand() % 6) + 1;
int y = (rand() % 6) + 1;
int result = 0;
int guess = 0;
printf("The values of two dice rolls will be added up. The aim is to guess whether that total number will be odd or even.\n");
printf("To guess odd, enter '1'. To guess even, enter '2'.\n\n");
printf("Please enter your guess for the combined total of the two dice rolls: ");
scanf_s("%d", &guess);
if (guess == 2)
{
printf("\nyour guess is even.\n");
}
if (guess == 1)
{
printf("\nyour guess is odd.\n");
}
if (guess > 2 || guess < 1)
{
printf("\nInvalid guess.\nYou lose!\n");
return (1);
}
printf("\ndice roll 1 = %d\n", x);
printf("dice roll 2 = %d\n", y);
result = x + y;
printf("\ncombined total of both rolls is %d", result);
if (result == 1 || result == 3 || result == 5 || result == 7 || result == 9 || result == 11)
{
printf("\ncombined total of both rolls is odd.\n");
}
else
{
printf("\ncombined total of both rolls is even.\n");
}
if (guess == 1 && result == 1 || guess == 1 && result == 3 || guess == 1 && result == 5 || guess == 1 && result == 7 || guess == 1 && result == 9 || guess == 1 && result == 11)
{
printf("\nYou win!\n");
}
else if (guess == 2 && result == 2 || guess == 2 && result == 4 || guess == 2 && result == 6 || guess == 2 && result == 8 || guess == 2 && result == 10 || guess == 2 && result == 12)
{
printf("\nYou win!\n");
}
else
{
printf("\nYou lose!\n");
}
return 0;
}
You should change scanf_s to scanf
The line if (result == 1 || result == 3 ... could be if (result % 2 == 1) {
You could use strcmp to solve your question
The following code could work:
//cho-han
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
int main(void)
{
srand(time(NULL));
int x = (rand() % 6) + 1;
int y = (rand() % 6) + 1;
int result = 0;
int guess = 0;
char buf[10];
printf("The values of two dice rolls will be added up. The aim is to guess whether that total number will be odd or even.\n");
printf("To guess odd, enter 'odd'. To guess even, enter 'even'.\n\n");
printf("Please enter your guess for the combined total of the two dice rolls: ");
fgets(buf, sizeof buf, stdin);
if (strcmp(buf, "even\n") == 0) {
guess = 2;
printf("\nyour guess is even.\n");
} else if (strcmp(buf, "odd\n") == 0) {
guess = 1;
printf("\nyour guess is odd.\n");
} else {
printf("\nInvalid guess.\nYou lose!\n");
return 1;
}
printf("\ndice roll 1 = %d\n", x);
printf("dice roll 2 = %d\n", y);
printf("\ncombined total of both rolls is %d", x + y);
result = (x + y) % 2;
if (result == 1)
printf("\ncombined total of both rolls is odd.\n");
else
printf("\ncombined total of both rolls is even.\n");
if (guess == result)
printf("\nYou win!\n");
else
printf("\nYou lose!\n");
return 0;
}
You need to change your guess to char type and scanf to capture string.
char guess[256];
scanf("%s", guess);
And then the best way would be to call toupper() and compare with your text using strcmp().

if..else if..else loop not executing properly

I'm writing a program that asks the user to input a three digit number then adds each number by 6 with a modulus of 10.
For example if I enter 619, the output I shall receive is 275.
My only problem is when I enter 100, I receive 1360, instead of 766 like I'm supposed to.
Here is what I have so far:
int main()
{
//declaring variables
int numbers, newNumbers, input;
int newInput = 0;
//User input
printf("Enter a three-digit number: ");
//reads input (%d) and stores it as "input" (&input)
scanf("%d", &input);
//check if input is 3 digits. If not, print message
if(input < 100 || input > 999)
{
printf("Invalid input, the number must be between 100 and 999 \n");
return 0;
}
//loops program until input is 0
while(input > 0)
{
//modulus 10
numbers = input % 10;
//adds 6 to input. Modulus 10
newNumbers = (numbers + 6) % 10;
//if input > 10, calculates new input
if(input > 100)
newInput = newNumbers;
else if(input > 10)
newInput = (newNumbers * 10) + newInput;
else
newInput = (newNumbers * 100) + newInput;
input /= 10;
}
//prints result
printf("Output: %d \n", newInput);
return 0;
}
In your code, by saying
if(input > 100)
newInput = newNumbers;
else if(input > 10)
newInput = (newNumbers * 10) + newInput;
you're not taking into account the numbers 100 and 10 themselves in the TRUE condition, whereas you should be counting them, too. You need to change the if condition to use >=, like
if(input >= 100)
newInput = newNumbers;
else if(input >= 10)
newInput = (newNumbers * 10) + newInput;
Hi an easier solution is just this one:
output = (input + 666) % 1000; //Add 6 to all numbers
if(input % 10 > 3) //Correct units carry
output-=10;
if(input % 100 > 30) //Correct tents carry
output-= 100;
It works and is easy scalable :)

C: Logical operators

In this code, the user must type his/her grade (1-10) on a subject and his/her absences(0-14) on it. If he/she gets >=5 grade and <=2 absences, the student passes.
I have a problem with the possibility that both grade and absences numbers are off the limits of the programme. Which are the "right" logical operators on this:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int gr, ap;
printf("GIVE YOUR SUBJECT GRADE:\n");
scanf("%d", &gr);
printf("GIVE YOUR SUBJECT ABSENCES\n");
scanf("%d", &ap);
if (ap >= 0 && ap <= 14 && gr >= 0 && gr <= 10)
{
if (gr >= 5 && ap <= 2)
printf("YOU PASSED!\n");
else if (gr < 5 && ap <=2)
printf("FAILED DUE TO YOUR GRADE\n");
else if (gr >= 5 && ap > 2)
printf("FAILED DUE TO YOUR ABSENCES\n");
else if (gr < 5 && ap > 2)
printf("FAILED DUE TO YOUR GRADE AND ABSENCES\n");
}
else
{
if (ap >= 0 && ap <= 14 && gr < 0 || gr > 10)
printf("FALSE GRADE NUMBER\n");
else if (gr >= 0 && gr <= 10 && ap < 0 || ap > 14)
printf("FALSE ABSENCES NUMBER\n");
//here is the problem
else if (gr < 0 || gr > 10 && ap < 0 || ap > 14)
printf("FALSE ABSENCES AND GRADE NUMBERS\n");
}
system("pause");
return 0;
}
Since && has priority over ||, you need parentheses here:
ap >= 0 && ap <= 14 && (gr < 0 || gr > 10)
// ^ ^
Otherwise, the condition is interpreted as
(ap >= 0 && ap <= 14 && gr < 0) || (gr > 10)
which causes issues down the line.
Same goes for the other two conditions - they should be as follows:
(gr >= 0 && gr <= 10) && (ap < 0 || ap > 14)
(gr < 0 || gr > 10) && (ap < 0 || ap > 14)
Note that when you keep evaluating the same conditions over and over it is better to make a variable that stores their result once, and use that variable after that:
int validGrade = gr > 0 && gr <= 10;
int validAbsences = ap >= 0 && ap < 14;
Now you can write code like this:
if (validGrade && validAbsences) {
...
} else {
if (validAbsences && !validGrade) {
...
} else if (!validAbsences && validGrade) {
...
} else {
...
}
}
You first check if gr is out of range but not ap, then you check if ap is out of range but not gr, and if neither of them is true then both must be out of range, and for that you only need an else statement last.
However, the two conditions above are wrong, change the || to &&. In fact, you don't really check both ap and gr, because if one is in range you know the other is out of range. So you can simplify it like this:
// If ap is in range, that means gr must be out of range
if (ap >= 0 && ap <= 14)
printf("FALSE GRADE NUMBER\n");
// else if gr is in range then ap must be out of range
else if (gr >= 0 && gr <= 10)
printf("FALSE ABSENCES NUMBER\n");
// else both ap and gr are out of range
else
printf("FALSE ABSENCES AND GRADE NUMBERS\n");
I also have another couple of suggestions, like using unsigned int instead, then the value can never be below zero. You could also use macros to ease maintainability and readability of the code.
Perhaps something like this:
#include <stdio.h>
#include <stdlib.h>
#define AP_IN_RANGE(ap) ((ap) <= 14)
#define GR_IN_RANGE(gr) ((gr) <= 10)
int main(void)
{
unsigned int gr, ap;
printf("GIVE YOUR SUBJECT GRADE:\n");
scanf("%u", &gr);
printf("GIVE YOUR SUBJECT ABSENCES\n");
scanf("%u", &ap);
if (AP_IN_RANGE(ap) && GR_IN_RANGE(gr))
{
if (gr >= 5 && ap <= 2)
printf("YOU PASSED!\n");
else if (gr < 5 && ap <=2)
printf("FAILED DUE TO YOUR GRADE\n");
else if (gr >= 5 && ap > 2)
printf("FAILED DUE TO YOUR ABSENCES\n");
else
printf("FAILED DUE TO YOUR GRADE AND ABSENCES\n");
}
else
{
if (AP_IN_RANGE(ap))
printf("FALSE GRADE NUMBER\n");
else if (GR_IN_RANGE(gr))
printf("FALSE ABSENCES NUMBER\n");
else
printf("FALSE ABSENCES AND GRADE NUMBERS\n");
}
}
Of course, you should really make sure that the user input if valid, so you need to check what scanf returns. This will protect against the user inputting some letters instead of a valid unsigned number.

C programming issue

I've created a simple guessing game. Pick a number between 0 and 100, depending on the number you enter the program will output hot, Warm, Cold or correct!. The number I've chosen to be the correct answer is 51. My program compiles and runs but always outputs correct! for every value I enter. Thanks for helping if you decide to.
int main(void)
{
int number, answer;
answer = 51;
printf("Enter a number between 0 and 100:\n");
scanf("%d", &number);
if ((number > 51) && (number <= 56) || (number < 51) && (number >= 46))
{
printf("Hot\n");
}
else if ((number > 56) && (number <= 66) || (number < 46) && (number >= 36))
{
printf("Warm\n");
}
else if ((number > 66) && (number <= 100) || (number <36) && (number >= 0))
{
printf("Cold\n");
}
else if ((number > 100) || (number < 0))
{
printf("Error number has to be between 0 and 100 - re run\n");
}
else (number = 51);
{
printf("Correct!\n");
}
system ("pause");
return 0;
}
This little snippet:
else (number = 51);
{
printf("Correct!\n");
}
is actually equivalent to:
else
(number = 51);
//=======================
{
printf("Correct!\n");
}
The first part of that is the else clause which, if activated, will set number to 51.
The second part is totally disconnected from the if statement section and is a standalone block that will execute no matter what.
If you must put the condition there for readability (and it would be == rather than =), you could do:
else // (number == 51)
{
printf("Correct!\n");
}
As an aside, you could make your code shorter and more readable by starting at the specific and moving to the general, something like (just replacing the if statement):
if (number == 51)
printf ("Correct!\n");
else if ((number >= 46) && (number <= 56))
printf ("Hot\n");
else if ((number >= 36) && (number <= 66))
printf ("Warm\n");
else if ((number >= 0) && (number <= 100))
printf ("Cold\n");
else
printf ("Error, number has to be between 0 and 100 - re run\n");
}
You don't need to ever check the two ranges (above and below) for "temperature" since the inner ranges have already been checked.
else (number = 51);
{
printf("Correct!\n");
}
can be re-written as
else
{
number = 51;
}
{
printf("Correct!\n");
}
So irrespective of what your number is the printf("Correct!\n"); gets executed.
It can be fixed like
else
{
printf("Correct!\n");
}
remove the condition from the else statement.
int main(void)
{
int number, answer;
answer = 51;
printf("Enter a number between 0 and 100:\n");
scanf("%d", &number);
if ((number > 51) && (number <= 56) || (number < 51) && (number >= 46))
{
printf("Hot\n");
}
else if ((number > 56) && (number <= 66) || (number < 46) && (number >= 36))
{
printf("Warm\n");
}
else if ((number > 66) && (number <= 100) || (number <36) && (number >= 0))
{
printf("Cold\n");
}
else if ((number > 100) || (number < 0))
{
printf("Error number has to be between 0 and 100 - re run\n");
}
else
{
printf("Correct!\n");
}
return 0;
}
your code says: if none of the if statements is satisfied, assign 51 to number. and then always print "Correct!\n".
In the last else statement, you should either use
else if (number == 51)
{
...
}
or
else
{
...
}

Resources