Nested if statement in C - c

My code need to execute only one case path from 3x2 table which is; for Male 140 to 160 cm: short, 161 to 180 cm: medium; 181 to 199 cm: tall and for Female 120 to 140 cm: short, 141 to 165 cm: medium and 166 to 180 cm: tall.
For example, if i enter 153 cm woman, output is need to be only medium. But now my code gives output if i enter 153 cm woman, medium & tall together at the end.
How can i edit this code so far to execute for only one case for two combinations, age and length, and one of the three option for length; for example if i enter 153 cm woman, it will need say only medium.
#include <stdio.h>
int main()
{
int length;
char gender;
printf("enter gender: ");
scanf("%c", &gender);
printf("enter length: ");
scanf("%d", &length);
if (gender == 'M' || 'm') {
if (length <= 140 && length <= 160 ) {
printf ("short");
}
if (length <= 161 && length <= 180 ) {
printf ("medium");
}
if (length <= 181 && length <= 199 ) {
printf ("tall");
}
if (gender == 'W' || gender == 'w') {
if (length <= 120 || length <=140) {
printf("short");
if (length <=141 || length <=165) {
printf ("medium");
if (length <=166 || length <=180) {
printf ("tall");}
else {
printf("error");
}
}
}
}
}
return 0;
}

For below lines, it has to be length >= 161.
Pls check similar lines for this.
if (length <= 161 && length <= 180 ) {
printf ("medium");
}

kadir you have done a number of mistakes , no problem . Practice makes a man perfect ...!
Compare your code and your code that i changed .. and realize the mistakes . Explanation is given as comments in code .
#include<stdio.h>
int main()
{
int length;
char gender;
printf("enter gender: ");
scanf("%c", &gender);
printf("enter length: ");
scanf("%d", &length);
if (gender == 'M' ||gender == 'm') { //comparison should be done in both sides of or
if (length >= 140 && length <= 160 ) {
printf ("short");
}
else if (length >= 161 && length <= 180 ) {
printf ("medium");
}
else if (length >= 181 && length <= 199 ) {
printf ("tall");
}
}
else if (gender == 'W' || gender == 'w') {
if (length >= 120 && length <=140) {
printf("short");
}
else if (length >=141 && length <=165) { // & should be used.
printf ("medium");
}
else if (length >=166 && length <=180) {
printf ("tall");}
else { /* if you are using else simply , it corresponds to the last if not all the if's in front so try using if else .*/
printf("error");
}
}
return 0;
}
Good Luck

You need to compare length in an exclusive range. Here is the code:
#include <stdio.h>
int main()
{
int length;
char gender;
printf("enter gender: ");
scanf("%c", &gender);
printf("enter length: ");
scanf("%d", &length);
if (gender == 'M' || gender == 'm'){
if (length <= 160 )
printf ("short\n");
if (161 <= length && length <= 180)
printf ("medium\n");
if (181 <= length && length <= 199)
printf ("tall\n");
}
if (gender == 'W' || gender == 'w'){
if (length <= 140)
printf ("short\n");
if (141 <= length && length <= 165)
printf ("medium\n");
if (166 <= length && length <= 180)
printf ("tall\n");
if(length>=180)
printf("error \n");
}
else if(gender != 'm'|| gender!='M'|| gender!='w'||gender!='W')
printf("error");
return 0;
}

Related

fgets wants input twice

I'm still quite new to C and do have problems with how to indent code, so I apologise for this in advance. I am trying to get the programme to input strings and output readability score. I have the code all written out, however, whenever input a phase and press enter the programme doesn't execute the rest of the code, instead I have to input something else before moving on. I have no idea why! Please could someone help?
#include <string.h>
#include <stdlib.h>
#include <math.h>
int main(void)
{
char str[500]; // think of this like an array
int alphabet =0 , i =0, word=0, special_characters =0, vowels = 0;
printf("Input the string:\n");
fgets(str,500,stdin); // <== issue here where I have to input string twice for while loop to occur!
/* Checks each character of string*/
while(str[i] !='\0')// while there is a character and not empty space
{
if(str[i] == 'a' || str[i] == 'e' || str[i] == 'i' ||
str[i] == 'o' || str[i] == 'u' || str[i] == 'A' ||
str[i] == 'E' || str[i] == 'I' || str[i] == 'O' ||
str[i] == 'U')
{
++vowels;
}
else if((str[i] ==' ' || str[i]=='\n' || str[i]=='\t'))
{ // if there is not space, tab or enter, then logically there is a word
word++; // after not finding a space it is told to look for next one
}
else if((str[i] =='?' || str[i]=='!' || str[i]=='.')) // looks for sentance enders
{
special_characters++; // keeps going until text ends
}
else if((str[i]>='a' && str[i]<='z') || (str[i]>='A' && str[i]<='Z'))
{
// only i is just a counter of each letter in
// this case. alphabet is told to increase
alphabet++; // made this a loop that goes onto next letter
}
i++; // tells i to scan over ALL if loops by being INSDIE the while loop but not
// part of the IF statements!
}
//L = Letters ÷ Words × 100 = 639 ÷ 119 × 100 ? 537
//S = Sentences ÷ Words × 100 = 5 ÷ 119 × 100 ? 4.20
double letters = vowels + alphabet;
double w = word;
double d = 100.0;
double L = (letters/w)*d;
double e = special_characters; // sentances
double S= (e/w)*100;
scanf("%lf",&S);
double index = (0.0588 * L) -(0.296 * S)- 15.8;
scanf("%lf",&index);
double round(double index);
if(index <=1)
{
printf("Below Grade 1\n");
}
else if(index >=3 && index <4)
{
printf(" Grade 3\n");
}
else if(index >=5 && index <6)
{
printf(" Grade 5\n");
}
else if(index >=7 && index <8)
{
printf(" Grade 7\n");
}
else if(index >=8 && index <9)
{
printf(" Grade 8\n");
}
else if(index >=9 && index <10)
{
printf(" Grade 9\n");
}
else if(index >=10 && index <11)
{
printf(" Grade 9\n");
}
else if(index >=16)
{
printf(" Grade 16+\n");
}
}
Your problem is likely further down on the scanf()
Try
// ...
double S= (e/w)*100;
printf("Enter value for S:\n"); // suggestion for feedback
if (scanf("%lf", &S) != 1) {
//scanf failed
fprintf(stderr, "scanf failed.\n");
exit(EXIT_FAILURE);
}
//...

Problem with inputing only a number from 1 to 1000

Working on Ubuntu
I have a problem with my code and i dont know how to fix. Maybe there is a function that will help me with that.
I want to input a string and then my program need to check if it is a number from 1 to 1000. If there is a letter or a symbol
Here is my code:
char tab[200]="";
int i;
scanf("%199[^\n]s",tab);
for(i=0;i<200;i++)
{
if(tab[i] >= 'A' && tab[i]<='Z')
{
printf("Big letters\n");
}
else if(tab[i] >= 'a' && tab[i]<='z')
{
printf("Small letters\n");
}
}
if(strlen(tab) == 4 && tab[3] > 0 && tab[2] > 0 && tab[1] > 0 && tab[0] > 1)
{
printf("Bigger then 1k\n");
}
else if(strlen(tab) > 4)
{
printf("Longer then 4 chars\n");
}
It's not working properly and it also doesnt include symbols...
I've found code like this but im not sure how to make my number less then 1001
char input[MAXINPUT] = "";
int length,i;
int number;
printf(" id: \n");
fgets(input, MAXINPUT, stdin);
number = atoi(input);
length = strlen (input);
for (i=0;i<length; i++)
if (!isdigit(input[i]))
{
printf ("Entered input is not a number\n");
exit(1);
} else if (number < 1001)
printf ("Given input is a number\n");
Not sure if i am using fgets properly here.
Before u will send me to here
, please read my question
Use This.. Maybe This Help. You can Modify it on your Choice.
#include<string.h> // header file for strlen()
void method()
{
char tab[200]="";
int i;
scanf("%199[^\n]s",tab);
for(i=0;i<strlen(tab);i++) // Loops only to the lenght of total vlaues in array
{
if(tab[i] >= 65 && tab[i]<=90) // Ascii Value of Capital Ltrs
{
printf("Big letter\n");
}
else if(tab[i] >= 97 && tab[i]<=122) // Ascii Value of Small Ltrs
{
printf("Small letter\n");
}
else if(tab[i] >= 48 && tab[i]<=57) // Ascii Value of Numbers
{
printf("Number\n");
}else // of else other numebrs are all Symbols but can be
{
printf("Symbols\n");
}
}
}
Please note that you're compareing characters with integers (numbers). The character '1' in ascii is 49, as an example, while you have been using the numeric value 1 in the comaprisons. Test to add single quotation marks similar to those around your letter comparisons and see if you don't get a different result.
Best regards
Esbjörn

How to read string in structure with space? [duplicate]

This question already has answers here:
Reading string from input with space character? [duplicate]
(13 answers)
Closed 5 years ago.
Our corporation office requires an application which will maintain all registered Universities in Chennai and that application should be user friendly in terms of searching a University. Create a structure called “University” with the following attributes: name, license number and area code.
Requirement: License number for a university should be 6 digits and the first 2 digits must be alphabets of Upper case letters and last 4 digits must be number.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct University
{
char name[100];
char license[10];
int area;
}u[10];
void main()
{
int i, n, r, k = 0, flag = 1, f2 = 1, j, search = 0;
char s[100];
printf("Enter the number of records\n");
scanf("%d", &n);
printf("Enter the details of %d universities\n", n);
for (i = 0; i<n; i++)
{
printf("Name of the University\n");
getchar();
scanf("%s", u[i].name);
j = strlen(u[i].name);
if (j <= 1)
{
f2 = 0;
break;
}
printf("License Number\n");
scanf("%s", u[i].license);
k = strlen(u[i].license);
if (k<1)
{
f2 = 0;
break;
}
if (k<6)
{
flag = 0;
}
else if ((u[i].license[0] >= 'A' && u[i].license[0] <= 'Z') && (u[i].license[1] >= 'A' && u[i].license[1] <= 'Z') && (u[i].license[2] >= '0' && u[i].license[2] <= '9') && (u[i].license[3] >= '0' && u[i].license[3] <= '9') && (u[i].license[4] >= '0' && u[i].license[4] <= '9') && (u[i].license[5] >= '0' && u[i].license[5] <= '9') && k == 6)
{
flag = 1;
}
else
{
flag = 0;
}
printf("Area Code\n");
scanf("%d", &u[i].area);
//printf("%d",u[i].area);
if (u[i].area <= 0)
{
f2 = 0;
}
}
if (flag == 0)
{
printf("Sorry! You have entered incorrect license number.");
}
else if (f2 == 0)
{
printf("Unable to continue");
}
else
{
printf("Enter the name of the University to be searched\n");
scanf("%s", s);
for (i = 0; i<n; i++)
{
if ((strcmp(u[i].name, s)) == 0)
{
search = 1;
}
}
if (search == 1)
{
printf("University is licensed one.");
}
else
{
printf("University is not found.");
}
}
}
when I give number of university as 3, then it did not take input for the 3rd university.
Test Case
Input 1
Enter the number of records
3
Enter the details of 3 universities
Name of the University
SRM
License Number
SR1234
Area Code
28
Name of the University
University of Madras
License Number
SP0904
Area Code
18
Name of the University
Bharath University
License Number
BU0101
Area Code
35
Enter the name of the University to be searched
SRM
Output 1
University is licensed one.
Seems like you are interested in just reading a c-string containing a space. To do that you can use fgets. Here is a toy program:
#include <stdio.h>
#include <string.h>
struct s {
char name[100];
int something;
};
int main(void)
{
struct s myStruct;
printf("%s", "Enter name: ");
fgets(myStruct.name, 100, stdin);
myStruct.name[strlen(myStruct.name) - 1] = '\0'; //This should remove the newline char at the end
printf("Name is: %s", myStruct.name);
}

if else statement not giving expected answer

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

Why does my if statement create an infinite loop?

The code works for every if statement except for the first one where if the statement is true, it proceeds to create an infinite loop of "Enter a student mark [0.00, 100,00] : " and "No input accepted!".
#include <stdio.h>
#define MIN 0
#define MAX 100
int getMark(void) {
int mark;
char ch;
int repeat = 1;
printf("Enter a student mark [0, 100] : ");
int r = scanf("%i%c", &mark, &ch);
if (r == 0) {
printf("**No input accepted!**\n");
}
else if (ch != '\n') {
printf("**Trailing characters!**\n");
}
else if (mark < MIN || mark > MAX) {
printf("**Out of range!**\n");
}
return mark;
}
int main() {
int mark;
do {
mark = getMark();
} while (mark != 0);
}
What's causing it to loop and how do I fix it?
1) If you input a string or just a char value you must remove it from your input stream before using it.
#include <stdio.h>
#define MIN 0
#define MAX 100
int getMark(void) //Funtion for marks input
{
int mark;
char ch;
//int repeat = 1;
char c;
printf("Enter a student mark [0.00, 100,00] : ");
int r = scanf("%d %c", &mark, &ch);
if (r == 0) //Input begins with a letter
{
printf("**No input accepted!**\n");
}
else if(ch == '\n') //Input ends with a letter
{
printf("**Trailing characters!**\n");
}
else if( mark < MIN || mark > MAX) //Range
{
printf("**Out of range!**\n");
}
//Remove the previous string from the input stream
while ( (c = getchar()) != '\n' && c != EOF );
return mark;
}
int main()
{
int mark;
do
{
mark = getMark();
}while (mark != 0);
return 0;
}
Output
Enter a student mark [0.00, 100,00] : -10 c
**Out of range!**
Enter a student mark [0.00, 100,00] : 101 b
**Out of range!**
Enter a student mark [0.00, 100,00] : 50 a
Enter a student mark [0.00, 100,00] : abcd
**No input accepted!**
Enter a student mark [0.00, 100,00] : 0 q
The problem is that with no input accepted the variable mark will be uninitialized and might be something else that 0. Your while loop will then continue forever without updating mark.

Resources