Codecademy Race Day else statment isn't working - if-statement

Here's my code for this test project. My else statement isn't returning when my age is set to 18. Ignore the change in double/single quotes; I accidentally clicked on the Clean Up button and Codecademy switched them.
let raceNumber = Math.floor(Math.random() * 1000);
const early = true;
const age = 18;
if (early && age > 18) {
raceNumber += 1000;
console.log("Your race starts at 9:30am, and your number is " + raceNumber + ".");
} else if (!early && age > 18) {
console.log("Your race starts at 11:00am, and your number is " + raceNumber + ".");
} else if (early || !early && age < 18) {
console.log('Your race starts at 12:30pm, and your number is ' + raceNumber + '.');
} else {
console.log('Please see the registration desk for your race time and number');
}

If early is always true, then early || !early && age < 18 is true, and the final else will never be reached.
You might be in need of some parentheses

Related

Kickstart 2020 RoundG Problem A Runtime Error

I am trying to solve the problem "Kick Start" from round G from last year. In short you need to count the number of appearances of the substring "KICK....START" with any number of characters in between the two words. The input is a string with only capital letters.
I wrote some code and the sample works fine. But after sending the code I get a runtime error in the first test case. I Have tried many different things like using the at() function from string, or substring but nothing has solved the problem. Any ideas what the problem could be?
So my function that gets the error looks like this:
long long fragment_count = 0;
long long open_count = 0;
string text;
cin >> text;
for (int i = 0; i < text.size() - 4; ++i) {
if (text[i] == 'K') {
if (text[i + 1] == 'I' && text[i + 2] == 'C' && text[i + 3] == 'K') {
open_count++;
}
} else if (text[i] == 'S') {
if (text[i + 1] == 'T' && text[i + 2] == 'A' && text[i + 3] == 'R' && text[i + 4] == 'T') {
fragment_count += open_count;
}
}
}
cout << fragment_count << "\n";
Edit: Outside of this function is the template I use for the kickstart problems. At the start there are two lines that I read that speed up io:
ios::sync_with_stdio(0);
cin.tie(0);
Then I just read a number with cin, that signifies the test cases and call the fucntion above for every test case.
text.size() is of type std::size_t, which is an unsigned type. If the length of the text is less than 4, text.size() - 4 wraps around and becomes a huge positive number.
Replace the comparison with i + 4 < text.size().

Creating an array using a Do While loop (with input validation)

I am making a C++ code where you will create an array using a do while loop.
Here is the full code:
const int size = 10;
double *pt1;
//executable
pt1=new double[size];
int i = 0;
do{
cout <<"mile" << "[" << i << "]" << setw(3);
if(*(pt1+i) >= 100 && *(pt1+i) <= 250)
{
cin >> *(pt1+i);
i++;
}
else if( *(pt1+i) > 100 && *(pt1+i) < 250)
{
cout << "100-250 only";
continue;
}
}while(i < 10);
There is an input validation where the numbers that will be accepted are only numbers from 100 to 250 but it keeps on looping. I can't find where the problem is. Any help would be greatly appreciated!
The first error is that you are testing the value of the input before you actually get the input. That makes no sense, you need to switch the order around. So this
if(*(pt1+i) >= 100 && *(pt1+i) <= 250)
{
cin >> *(pt1+i);
...
}
else if( *(pt1+i) > 100 && *(pt1+i) < 250)
{
...
}
should be this
cin >> *(pt1+i);
if(*(pt1+i) >= 100 && *(pt1+i) <= 250)
{
...
}
else if( *(pt1+i) > 100 && *(pt1+i) < 250)
{
...
}
Secondly I think you meant
else if( *(pt1+i) < 100 || *(pt1+i) > 250)
Or better you could have just said
else
Then there is no chance of getting the logic wrong. When you have only two choices, you just need to test for the first choice and use else for the second choice. There's no need to test for the opposite of the first choice, using a plain else will do that automatically.
Also continue at the end of a loop is not necessary, loops continue automatically.
Finally pt1[i] is much easier to read than *(pt1+i).

Unable to get desired output for the problem

I am trying to solve a problem here. I have two arrays which needs to be added and produce a desired output. {'A','A','A','B','A','X','M'} and {'A', 'B', 'A', 'A', 'B', 'A', 'B', 'B'}. Value of A is 10 and B is 20.
If A or B are repeated consecutively then the bonus numbers are added which is 10. I need to get an output of total score of 90 for first and 140 for second. How Can I write the perfect code.
My Code here is as below: The output should be 90 for the first array and 140 for a second. X and M have 0 value. SO don't mind them.
Here First character in array is A so score is 10
Second is also A so now 10 for A and as the previous was A so 10+10 = 20
Now as third one is also A add another 10 to previous score as 10 + 20(as last two were two as well ) ie. 30
Now fourth element in array is B so its not A and Streak is Broken so add Score For B which is set as 20
For Fifth Element we have A but as previous was Blue so no streak bonus and score of A was reset so add 10 now
Add 0 for X and M element
hence total score is 10+20+30+20+10 = 90
#include <iostream>
int main()
{
int currentEScore = 0;
int TotalScore = 0;
char Box[] = { 'A', 'A', 'A', 'B', 'A', 'X', 'M' };
// A B A R A R A A
for (int i = 0; i < Box[i]; i++) {
if (Box[i] == 'A') {
currentEScore = 10;
if (Box[i - 1] == Box[i]) {
currentEScore += 10;
TotalScore = TotalScore + currentEScore;
}
else {
TotalScore = TotalScore + currentEScore;
}
}
else if (Box[i] == 'B') {
currentEScore = 20;
if (Box[i - 1] == Box[i]) {
currentEScore += 10;
TotalScore = TotalScore + currentEScore;
}
else {
TotalScore = TotalScore + currentEScore;
}
}
else {
currentEScore = 0;
}
}
std::cout << TotalScore;
}
First things first: You are accessing the array out-of-bounds in the first iteration (if (Box[i - 1] == Box[i])). That is undefined behavior and strictly speaking all your code is meaningless, because a compiler is not mandated to do anything meaningful with invalid code. It just happens that this does not affect the outcome of your code. This is the worst incarnation of undefined behavior: It appears to work. You need to fix that.
Next, your loop reads for (int i = 0; i < Box[i]; i++) { and the condition cannot be correct. Again this makes your loop access the array out-of-bounds. I am a bit puzzled how this worked (I didnt realize it myself first). This also has to be fixed! I suggest to use a std::string for character arrays. It is much less error prone and it has a size() method to get its size.
The above issues didn't affect the output (nevertheless they have to be fixed!), so now lets look at the logic of your code. But first a disclaimer: Really the best advice I can give you is to not continue reading this answer. The problem you are facing is a good opportunity to learn how to use a debugger. That is a skill you will need always. If you still decide to read the following, then at least you should try to forget everything this answers says and go trough the same process on your own, by either using a debugger or a piece of paper and a pen.
Lets go step by step in your first example { 'A', 'A', 'A', 'B', 'A', 'X', 'M' }
first character is A
if (Box[i] == 'A') -> condition is true
currentEScore = 10; -> currentEScoe == 10
(we ignore the out-of-bounds for a moment)
TotalScore = TotalScore + currentEScore; -> TotalScore == 10
next character is A
if (Box[i] == 'A') -> condition is true
currentEScore = 10; -> currentEScore == 10
if (Box[i - 1] == Box[i]) -> yes
currentEScore += 10; -> currentEScore == 20
TotalScore = TotalScore + currentEScore; -> TotalScore == 10+20 == 30
next character is A
if (Box[i] == 'A') -> condition is true
currentEScore = 10; -> currentEScore == 10 -> stop... this is wrong !
You are resetting the bonus score on each character and then only check for the previous one. The effect is that you never give bonus more than 20.
Solution: Fix the out-of-bounds access and only reset the bonus when the character is different from the last. Also the code can be simplified a bit, by realizing that the bonus is indepenent from whether the character is A or B. You only have to check if it is the same as the last, hence calculating the bonus and adding points for A and B can be done seperately:
#include <iostream>
#include <string>
int main()
{
int bonus_increment = 10;
int bonus = 0;
int score_A = 10;
int score_B = 20;
int TotalScore = 0;
std::string Box{"AAABAXM"};
for (size_t i = 0; i < Box.size(); i++) {
// determine bonus
if ( i > 0 && Box[i] == Box[i-1] ) {
bonus += bonus_increment;
} else {
bonus = 0;
}
// accumulate score
if (Box[i] == 'A') {
TotalScore += score_A + bonus;
} else if (Box[i] == 'B') {
TotalScore += score_B + bonus;
}
}
std::cout << TotalScore;
}
Don't forget what I said above. You waste this exercise if you simply copy this code and assume that you completed the exercise by doing so.
Here's I have made some changes with your code with minimal optimization.
It'll work for you. Please check it and let me know it's working or not.
#include <iostream>
int main()
{
int currentEScore = 0;
int TotalScore = 0;
char Box[] = {'A','A','A','B','A','X','M'};
// A B A R A R A A
for (int i = 0; i < Box[i]; i++) {
if (Box[i] == 'A') {
if (Box[i - 1] == Box[i]) {
currentEScore += 10;
}
else {
currentEScore = 10;
}
}
else if (Box[i] == 'B') {
if (Box[i - 1] == Box[i]) {
currentEScore += 10;
}
else {
currentEScore = 20;
}
}
else {
currentEScore = 0;
}
TotalScore = TotalScore + currentEScore;
}
std::cout << TotalScore;
}

In C++, using a loop to find the # of days on any given date?

And yes this is an assignment-- So please don't post solutions, but detailed pseudocodes are extremely helpful!
I already have a program in C++ that accepts a date from the user and will determine if it is a leap year or not.
Here is my leap year function so far (I do hope that this is the correct logic):
bool isLeapYear (int year){
int leapYear = 0;
//leapyear = 1 when true, = 0 when false
if ((year%400 == 0) && (year%100 != 100)) {
leapYear = 1;
}
else if (year%4 == 0) {
leapYear = 1;
}
else {
leapYear = 0;
}
if (leapYear == 1) {
return 1;
}
else {
return 0;
}
}
Here is a paraphrase of what I must do next:
You MUST use a loop that adds months one at a time to an accumulated sum.
Don't use any hardcoded values
Such as 152 for the first 5 months in a leap year
And to clarify, this is my first programming class and have been in this C++ class for just about a month now.
So it would be greatly appreciated if anyone could help me figure out how to do the loop statements to add the number of the months?
(IE: 12/31/2013 should be "365" in a non leap year, and "366" in a leap year).
I know this is wrong but this is what I have so far for a function "dayNumber" that simply return the number of days in the year to the main function (which is calling the dayNumber function):
int dayNumber (int day, int month, int year){
//variable declarations
int sumTotal = 0;
for ( int loop = 1; loop < month; loop++) {
sumTotal = (( month-1 ) * 31);
sumTotal = sumTotal + day + 1;
if ( (loop==4) || (loop=6) || (loop=9) ||
(loop==11) ) {
sumTotal = ( sumTotal - 1 );
}
else if ( isLeapYear(year) == 1 ) {
sumTotal = (sumTotal - 2);
}
else {
sumTotal = (sumTotal - 3);
}
}
return sumTotal;
}
I started to mess around with it to get to a proper value for days I knew but it kind of messed it up more, haha.
If anyone has any guidance on how to appropriately do a loop, I would be extremely greatful!:)
EDIT:
Alright, I think I may have answered my own question.
int dayNumber (int day, int month, int year){
//variable declarations
int sumTotal = 0;
for ( int loop = 1; loop < month; loop++) {
sumTotal = ( sumTotal + 31 );
if ( (loop==4) || (loop==6) || (loop==9) ||
(loop==11) ) {
sumTotal = ( sumTotal - 1 );
}
}
if ((month !=2) && (month > 1)) {
if (isLeapYear(year) ==1) {
sumTotal = ( sumTotal - 2 );
}
else {
sumTotal = ( sumTotal - 3);
}
}
else {
sumTotal = sumTotal;
}
sumTotal = sumTotal + day;
return sumTotal;
}
I definitely need to work on my loops.
I appreciate letting me know that my '=' should have been '=='!
I believe this is an appropriate code using a simple enough loop?
I will test some more dates. I've only tested the few provided on the class site so far.
I can't answer my own posts, I don't have enough reputation.
I know an answer has been accepted, but it took me some time writing my own, let's see if it can adds some informations overall.
Let's review this slowly.
First, your isLeapYear() function isn't completely right.
Without delving into the algorithm part, two or three things can be improved.
You're returning a bool, yet your return statements are returning ints. This isn't wrong in itself, but using the true and false keywords can improve the readability and consistency.
Instead of creating, assigning and returning a variable, you should instantly return your result.
Add spaces around your operators : year%400 should become year % 400.
Now your code.
This condition :
if ((year%400 == 0) && (year%100 != 100))
... especially this part :
(year%100 != 100)
Isn't doing what you expect.
Overall, the algorithm is as follow :
if year is not divisible by 4 then common year
else if year is not divisible by 100 then leap year
else if year is not divisible by 400 then common year
else leap year
Translating it in code:
/**/ if (year % 4 != 0)
return false;
else if (year % 100 != 0)
return true;
else if (year % 400 != 0)
return false;
else
return true;
Now let's simplify this a bit:
/**/ if (year % 4 == 0 && year % 100 != 0)
return true;
else if (year % 400 == 0)
return true;
else
return false;
Again:
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
return true;
else
return false;
And finally, the whole boolean expression can be directly returned:
return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
Now that your function is correct, let's try an algorithm to your dayNumber function :
If the date provided in parameters is considered correct, then the algorithm is quite simple :
Start sum from 0
Loop from 1 to month excluded
If month is Frebruary then add 29 if isLeapYear returns true, else 28
If month is January, March, May, July, August, October or December add 31
Else add 30
Add day to sum.
I know that giving detailed pseudocode helps more than a solution, but I'm not that good of a teacher yet :/ Good luck with this answer, and get some sleep when you're done :)
I'm assuming that dayNumber(8, 3, 1914) is supposed to return the ISO day number of 1914, March 8th.
What you want to do is the following:
procedure dayNumber(theDay, theMonth, theYear):
set answer to 1 // the first day of the year is day 1
for every month 'thisMonth', up to and excluding theMonth:
increment answer by the number of days in thisMonth
increment answer by (theDay - 1) // the first day of the month is monthday 1
return answer
In the iteration statement (or 'loop body'), there are three cases:
February: if it's a leap year, increment thisMonth by 29, otherwise increment by 28.
Short months (April, June, September, November): increment by 30 days.
Otherwise, long months (January, March, May, July, August, October, December): increment by 31 days.
This translates to:
if (thisMonth == 2) {
// February
if (isLeapYear(theYear))
thisMonth += 29;
else
thisMonth += 28;
} else if (thisMonth == 4 || thisMonth == 6 || thisMonth == 9 || thisMonth == 11) {
// Short month
thisMonth += 30;
} else {
// Long month
thisMonth += 31;
}
(Note: X += Y is, or should be, short for X = X + Y.)
The loop logic you use looks mostly correct to me, except for 1) off-by-one errors because you start with day 0, and 2) adding the monthday inside the loop rather than outside of it:
int dayNumber (int theDay, int theMonth, int theYear) {
int result = 1;
for (int thisMonth = 1; thisMonth < theMonth; thisMonth++) {
/* ... see above ... */
}
return result + theDay - 1;
}
Now, about making the iteration statement prettier, there are basically two ways (and if your course hasn't yet covered them, I of course recommend against using them in an answer). One is using a switch statement, but I'm really not a fan of them, and it doesn't provide much benefit over the code I already gave. The other would be to use arrays:
int dayNumber (int theDay, int theMonth, int theYear) {
int monthDays[12] = { 31, 28, 31, 30, 31, 30, 31
, 31, 30, 31, 30, 31 }
int result = 1;
for (int thisMonth = 1; thisMonth < theMonth; thisMonth++) {
if (thisMonth == 2 && isLeapYear(theYear))
// Special case: February in a leap year.
result += 29;
else
/* Take the month length from the array.
* Because C++'s array indices begin at 0,
* but our first month is month 1,
* we have to subtract one from thisMonth.
*/
result += monthDays[thisMonth - 1];
}
return result + theDay - 1;
}
#include <ctime>
static int GetDaysInMonthOfTheDate(std::tm curDate)
{
std::tm date = curDate;
int i = 0;
for (i = 29; i <= 31; i++)
{
date.tm_mday = i;
mktime(&date);
if (date1->tm_mon != curDate.tm_mon)
{
break;
}
}
return i - 1;
}

Working with embedded if and else if statements C++

Heres my code im trying to get tidied up for school, in the embedded if and else if statements it show errors when I try to compile.
errors : expect primary-expression before "else"
expected ';' before else
both of these come up for each line.
// This is a program to Calculate the volume of the sphere using the radius (a03.cpp)
// Written by: Jimmy Scott
// Date: 2/1/12
// Sources: Stackoverflow.com (else and if statements)
#include <iomanip>
#include <iostream>
#include <string>
using namespace std;
int main ()
{
char vehicle;
float total;
char over20;
char old;
int adults;
int oldpass;
char height;
int youngpass;
int bicycles;
float length;
cout<<"Fare Calculator by Jimmy Scott";
cout<<"\n\n\n Are You Bringing a vehicle on The Ferry ?";
cin>>vehicle;
if (vehicle == 'y')
{
cout<<"\n\n"<<"Is the Driver over 65 Years of age or disabled?";
cin>>old;
cout<<"\n\n"<<"Passengers going along with the driver"<<"\n\n";
cout<<"Adults (19-64 Years old):";
cin>>adults;
cout<<"\n\n"<<"Senior Citizens or disabled:";
cin>>oldpass;
cout<<"\n\n"<<"Young passengers 5-18 years old: ";
cin>>youngpass;
cout<<"\n\n"<<"Is your Vehicle over 7ft, 6in in height? ";
cin>>height;
cout<<"Vehicle length in feet: ";
cin>>length;
if (old == 'y')
{
total= 44.60;
}
else if (old == 'n');
{
total= 51.20;
}
else if (length < 20) and (height == 'y');
{
total= 102.4;
}
else if (length > 20) and (length < 30);
{
total= 76.80;
}
else if (length > 20) and (length < 30) and (height = 'y');
{
total= 153.60;
}
else if (length > 30) and (length < 40);
{
total= 204.80;
}
}
else
{
cout<<"\n\n"<<"How many Senior Citizens or disabled are in your group?";
cin>>oldpass;
cout<<"\n\n"<<"How many adults are in your group?:";
cin>>adults;
cout<<"\n\n"<<"How many in your group are youths (5-18):";
cin>>youngpass;
cout<<"\n\n"<<"How many in your group have Bicycles:";
cin>>bicycles;
total=oldpass * 6.55;
total= total + (adults * 13.15);
total= total + (youngpass * 10.55);
total= total + (bicycles * 4.00);
}
cout<<"\n\n"<<"your total fare cost is : $"<<total;
cout<<"\n\n\n"<<"Press <Enter> to Exit";
cin.ignore();
cin.get();
return 0;
}
Several things:
When you do a conditional, don't follow the test directly with a semicolon, as this stops the conditional statement and will do something different from what you want. Furthermore, since it terminates the if-else group, you will generate an error on the next 'else' statement.
You also need to enclose your conditional tests with parenthesis.
Here is an example of a correct else if statement:
else if ((length > 30) and (length < 40))
{
total= 204.80;
}
Update: I initially said to use && instead of 'and'. As honk says 'and' is a valid operator in c++ that does the same thing as &&. I prefer to use && for portability with c though.
eliminate all the ';' after the if else() statements. Also add '( )' if you make many conditions.