Difficulty with testing for ranges of integer values - c++

I am writing filter program grouping kindergarten, preschool and school for ages I wrote if program but it outputs conditions wrong who is willing to take look at my program?
#include<iostream>
using namespace std;
int main() {
int input;// age
int kindergarden , preschool , school;
cin >> input;
if (2 <= 4)
{
cout << "kindergarden" << "\n\n";
if (5 <= 6)
{
cout << "preschool" << "\n\n";
}
else (7 <= 15);
{
cout << "school" << "\n\n";
}
}
}

Your first if statement is if (2 <= 4). This will always be true. 2 is always less than 4. Inside that if statement, is another if statement, asking if 5 <= 6. This will always be true also. Thus, it will output "kindergarten preschool".
I assume you want to check if input is within the two values in your if statements. To do so, you would write
if(2 <= input && input <= 4)
Also, you should bring the second if statement outside of the first. To do that, you should put your } before the second if statement, not after the last one.
Edit: As YSC pointed out, there's another issue: else (7 <= 15);. There are two issues with this:
1) It should be else if(condition), as plain else statements do not expect a condition.
2) It should not end with ;. It should end with { to hold the code that should be executed if the condition is true.

Your first if is wrapped around two others. Because you 're used flat indentation of source code, it's very hard to spot.
if (2 <= input && input <= 4)
{
cout << "kindergarden" << "\n\n";
} // here was your mistake
else if (5 <= input && input <= 6)
{
cout << "preschool" << "\n\n";
}
else if (7 <= input && input <= 15) // ; another mistake
{
cout << "school" << "\n\n";
}
You can make it into one loop actually, in a dozen various ways
#include<iostream>
#include<string>
using namespace std;
int main() {
int input = 0;// age
const struct Cat
{
int age;
string category;
} classes[] = { {2, "kindergarden"}, {5, "preschool"}, {7, "school"}, {16, ""} };
cin >> input;
// without range loop this looks tricky
for(const Cat *c = std::end(classes)-1; c >= std::begin(classes); c-- )
if ( input >= c->age )
{
std::cout << c-> category;
break;
}
}
The only advantage would be aggregation of conditions in one place. Of course, there can be more parameters for condition, e.g. upper and lower bracket instead of lower only.

Related

if....else executing in the same time . Looking this problem for first time. Please anybody make me understand

I was solving a problem . Where i was comparing two array ,one is int and other is string .
inside for loop everything was fine until i inserted a else condition.Before else condition for loop was just fine . it was giving equel index for two array . But after else condition it was giving both the condition together.
here are my code-
#include <iostream>
#include <string>
using namespace std;
int main()
{
int last_digit[] = {61, 71, 11, 21, 32, 19, 27, 31};
string places[] = {"Brasilia", "Salvador", "Sao Paulo", "Rio de Janeiro", "Juiz de Fora", "Campinas", "Vitoria", "Balo Horizonte"};
int digit;
cin >> digit;
for (int i = 0; i <= 7; i++)
{
if (digit == last_digit[i])
cout << places[i]<< endl;
else
cout << "Sorry! no number." << endl;
}
Now i want to print the array values as index which is right without the else condition. But i when an input isn't in the array the program should give else condition once. But it is giving both if else condition. Here are my output .
emamulhaqueemon#Emams-MacBook-Air snake % cd "/Users/emamulhaqueemon/main/snake/" && g++ test.cpp -o test && "/Use
rs/emamulhaqueemon/main/snake/"test
11
Sorry! no number.
emamulhaqueemon#Emams-MacBook-Air snake %
now why this is happening and how can i make this right .Please anybody give the answers.
Your loop currently does too much:
find digit in last_digit
print corresponding element according to found digit
print no matching elements (whereas you want to print when find fails).
You might split that in smaller parts.
With functions from std, you might do:
const auto it = std::find(std::begin(last_digit), std::end(last_digit), digit);
if (it == std::end(last_digit)) { // Not found
std::cout << "Sorry! no number." << std::endl;
} else { // Found
const auto index = std::distance(std::begin(last_digit), it);
std::cout << places[index] << std::endl;
}
Demo
Just place the output statement in the else part of the if statement outside the for loop. For example
bool found = false;
for (int i = 0; i <= 7; i++)
{
if ( digit == last_digit[i])
{
found = true;
cout << places[i]<< endl;
}
}
if ( !found )
{
cout << "Sorry! no number." << endl;
}
If the array last_digit does not contain duplicate values and you need to find only the first occurrence of the value digit in the array then the loop can look the following way
for (int i = 0; !found && i <= 7; i++)
{
if ( digit == last_digit[i])
{
found = true;
cout << places[i]<< endl;
}
}
if ( !found )
{
cout << "Sorry! no number." << endl;
}

Reversing a number (C++)

I am brand new to C++, and am trying to make a simple program to determine if a user-entered integer is four digits, and if so, to reverse the order of said digits and print that output.
I have a (mostly) working program, but when I try, one of two things happens:
a) if line 16 is commented out and line 17 is active, then the program prints out an infinite number of reversed numbers and the IDE (in this case, repl.it) crashes; or
b) if line 17 is commented out and line 16 is active, then the program prints out one correct line, but the next line is "Your number is too short...again" (look at code below)
#include <iostream>
using std::string;
using std::cin;
using std::cout;
using std::endl;
int main() {
int n, reversedNumber, remainder;
bool loopControl;
char userFinalResponse;
reversedNumber=0;
cout<<"Input a 4 digit integer and press Return\n"<<endl;
cin>>n;
while (loopControl=true){
//if ((n>9999)||(n<1000))
if ((n>9999)||((n<1000)&&(n>0)))
{
cout<<"Your number is too short or too long. Please try again.\n"<<endl;
cin>>n;
loopControl=false;
} else {
while(n != 0)
{
remainder = n%10;
reversedNumber=reversedNumber*10+remainder;
n /= 10;
loopControl=true;
}//closing brace for reversal loop
cout<<"Your reversed number is "<<reversedNumber<<"\n"<<endl;
}//closing brace for else
}//closing brace for "while (loopControl>0){"
return 0;
}//closing brace for "int main() {"
You can try this:
int number = 1874 //or whatever you need
auto str = std::to_string(number);
if (str.length() == 4) {
std::reverse(str.begin(), str.end());
std::cout << str << std::endl;
}
I suggest you to give a look at the algorithm header that contains a lot of useful methods that can help you while developing programs.
According to the cpp tutorials = is the assignment operator, not the comparison operator. Because of this your while loop will never terminate. You can simply initialize loopControl to true, and then set it to false when it's okay to exit:
int n, reversedNumber, remainder;
bool loopControl = true; //Initialize to true
char userFinalResponse;
reversedNumber = 0;
cout << "Input a 4 digit integer and press Return\n" << endl;
cin >> n;
while (loopControl) {
//if ((n>9999)||(n<1000))
if ((n>9999) || ((n<1000) && (n>0)))
{
cout << "Your number is too short or too long. Please try again.\n" << endl;
cin >> n;
loopControl = true; //need to keep on looping
}
else {
while (n > 0)
{
remainder = n % 10;
reversedNumber = reversedNumber * 10 + remainder;
n /= 10;
loopControl = false; //Ok to exit
}//closing brace for reversal loop
cout << "Your reversed number is " << reversedNumber << "\n" << endl;
}
}

C++ do while loop not working

I'm trying to make this code work:
#include <iostream>
using namespace std;
int main()
{
int i;
do
{
cout << ("please enter a number between 1 and 10");
cin >> i;
} while(i > 10 && i < 1)
cout << "the square of the number you have entered is " << i*i;
}
Basically, the idea is that a user enters a number between 1 and 10. While the number is not between 1 and 10, it keeps asking the user to enter a number between the values. Then, when the number is between the values, it is squared and returned to the user.
I can't see why this isn't working
Any help is appreciated
You have:
while (i > 10 && i < 1)
You want:
while (i > 10 || i < 1)
while (i > 10 && i < 1)
Your condition is logically faulty; if reinterpreted, it says:
while i is greater than 10 AND i is less than 1
Judging from your code, the || operator should be used:
} while (i > 10 || i < 1);
As others mentioned, your condition is faulty.
a number can't obviously be under 1 AND above 10 at the same time, so the while loop exits immediately after the do statement.
#include <iostream>
using namespace std;
int main()
{
int i;
do
{
cout << ("please enter a number between 1 and 10");
cin >> i;
} while (i < 1 || i > 10)
cout << "the square of the number you have entered is " << i*i;
}
You should use an Or ||, that condition with && will never be true.
The loop condition is wrong and will never loop, as i cannot be less than 1 && greater than 10 at the same time. You should use the logical OR (||) operator instead. In addition, there must be a semicolon placed after the do-while statement. And you probably want and end of line placed after the prompt. Also, you don't want to start the bad habit of polluting the global namespace, even with the awesomeness of std. So:
#include <iostream>
int main()
{
int i;
do {
std::cout << "please enter a number between 1 and 10\n";
std::cin >> i;
} while (i > 10 || i < 1);
std::cout << "the square of the number you have entered is " << i*i << std::endl;
}

Reading from a txt file to a struct in c++ [duplicate]

This question already has answers here:
Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?
(5 answers)
Closed 9 years ago.
Why is the nr variable in my code incremented way above 5?
When I test how many times the while loop iterates, it cycles way more times than there are elements in my data file, I cannot understand why.
The data file contains - a 1 2 3 b
Here's my code:
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
struct SOMETHING
{
string string[10];
int int_1[100];
};
void main()
{
int nr = 0;
SOMETHING P;
ifstream D("data.txt");
while(!D.eof())
{
nr++;
if (nr == 1 || nr % 5 == 0)
{
D >> P.string[nr];
cout << P.string[nr] << " ";
}
D >> P.int_1[nr];
cout << P.int_1[nr] << " ";
}
D.close();
}
Examining this:
while(!D.eof())
{
nr++;
if (nr == 1 || nr % 5 == 0)
{
D >> P.string[nr];
cout << P.string[nr] << " ";
}
D >> P.int_1[nr];
cout << P.int_1[nr] << " ";
}
The reason your nr variable exceeds 5 is that you aren't resetting nr when your after each successful read of each line. I don't know if that's what you want, but the way you've implemented it has a problem (see below):
Your structure element clearly has space for 10 elements, but you're only checking and storing the elements at indices 1 and those which are multiples of 5: 0, 1, 5, 10, etc.
Using the eof method is bad practice as #P0W has noted in his comment. Use a while loop instead in tandem with std::getline.
The ifstream's internal pointer is not being updated, so the while loop will run indefinitely because eofbit is never set.

This program runs but not correctly; the numbers aren't right

this program runs but not correctly numbers arent right, i read numbers from a file and then when i am using them in the program they are not right.:brief decription of what i am trying to do can someone tell me if something doesnt look right.
this is what i have to do:
write a program that determines the grade dispersal for 100 students
You are to read the exam scores into
three arrays, one array for each exam.
You must then calculate how many
students scored A’s (90 or above), B’s
(80 or above), C’s (70 or above), D’s
(60 or above), and F’s (less than 60).
Do this for each exam and write the
distribution to the screen.
// basic file operations
#include <iostream>
#include <fstream>
using namespace std;
int read_file_in_array(double exam[100][3]);
double calculate_total(double exam1[], double exam2[], double exam3[]); // function that calcualates grades to see how many 90,80,70,60
//void display_totals();
double exam[100][3];
int main()
{
double go,go2,go3;
double exam[100][3],exam1[100],exam2[100],exam3[100];
go=read_file_in_array(exam);
go2=calculate_total(exam1,exam2,exam3);
//go3=display_totals();
cout << go,go2,go3;
return 0;
}
/*
int display_totals()
{
int grade_total;
grade_total=calculate_total(exam1,exam2,exam3);
return 0;
} */
double calculate_total(double exam1[],double exam2[],double exam3[])
{
int calc_tot,above90=0, above80=0, above70=0, above60=0,i,j, fail=0;
double exam[100][3];
calc_tot=read_file_in_array(exam);
for(i=0;i<100;i++)
{
for (j=0; j<3; j++)
{
exam1[i]=exam[100][0];
exam2[i]=exam[100][1];
exam3[i]=exam[100][2];
if(exam[i][j] <=90 && exam[i][j] >=100)
{
above90++;
{
if(exam[i][j] <=80 && exam[i][j] >=89)
{
above80++;
{
if(exam[i][j] <=70 && exam[i][j] >=79)
{
above70++;
{
if(exam[i][j] <=60 && exam[i][j] >=69)
{
above60++;
{
if(exam[i][j] >=59)
{
fail++;
}
}
}
}
}
}
}
}
}
}
}
return 0;
}
int read_file_in_array(double exam[100][3])
{
ifstream infile;
int exam1[100];
int exam2[100];
int exam3[100];
infile.open("grades.txt");// file containing numbers in 3 columns
if(infile.fail()) // checks to see if file opended
{
cout << "error" << endl;
}
int num, i=0,j=0;
while(!infile.eof()) // reads file to end of line
{
for(i=0;i<100;i++) // array numbers less than 100
{
for(j=0;j<3;j++) // while reading get 1st array or element
infile >> exam[i][j];
infile >> exam[i][j];
infile >> exam[i][j];
cout << exam[i][j] << endl;
{
if (! (infile >> exam[i][j]) )
cout << exam[i][j] << endl;
}
exam[i][j]=exam1[i];
exam[i][j]=exam2[i];
exam[i][j]=exam3[i];
}
infile.close();
}
return 0;
}
It's a bit hard to read your code, but when you're checking the score, you should be using chained else if statements and not nested ifs.
Something along the lines of:
if(exam[i][j] >=90 && exam[i][j] <=100)
{
above90++;
}
else if(exam[i][j] >=80 && exam[i][j] <=89)
{
above80++;
}
else if(...)
{...}
Also, you might want to pick a single syntax and be consistent with it throughout your code, it will make a HUGE amount of difference when trying to solve any problems, or even figuring out what on earth you were doing! It doesn't matter what way you go with as much as being consistent with it.
If statements allow you to do something if the conditional (the expression inside the parens) is true, and also if it's false.
if( /* statement that evaluates to true */ )
{
/* insert the commands you want to run when it's true here */
}
else
{
/* insert the commands you want to run when it's false here */
}
You can use the 'else' section to chain If statements together, this is useful if you have more than two possibilities. Such as this:
int number = 2; // Can be a value between 0 and 2 (0, 1, or 2)
if(number == 0)
{
cout << "The number is zero";
}
else if(number == 1)
{
cout << "The number is one";
}
else if(number == 2)
{
cout << "The number is two";
}
else
{
cout << "The value wasn't an allowed value!";
}
If number is between 0 and 2, it'll print out what number it is, and if it's not in that range, it'll print out a message saying it's not.
In addition to what others have stated, you need to look at your logic.
Example:
if(exam[i][j] <=90 && exam[i][j] >=100) {
...
}
Think about that for a minute. How can a number be <= 90 and simultaneously be >= 100?
Since you know how to write loops and functions, I suggest you change your design.
Create functions that operate on an Exam.
Create three separate Exam variables.
Call the functions on each Exam. In other words, only one exam will be passed as a parameter to a function.
Some example function names:
Exam_Calculate_Distribution
Output_Distribution
According to the minimal information you presented, the data is organized by rows of students and columns of scores. This would be the exception to the theme, since 3 exams would be easier to load.
In this assignment, the distribution may be easier to calculate using an array of 10 sections, each represent a range of 10. The calculation is simplified:
grade_index = grade / 10;
distribution[grade_index]++;
With this method, there is no need for using if-else statements. The cost is a few more memory cells for the extra slots in the array. In this case, I believe simplicity out weighs the extra used space.
One more step is required: after the distribution is calculated, sum up the regions 0 through 5. This represents the failures (F grades).
You will have to figure out how to handle the special case of a perfect score.
Remember, if your program is too complex for you to understand, you probably need to review the design.
Programs should be a simple as possible but no simpler. -- paraphrasing Albert Einstein.