Working with embedded if and else if statements C++ - 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.

Related

C++ coder for marks need help fixing it

I was trying to learn c++ i wanted to find marks using the code the issue is that it is not giving me the correct output and i wanted it to loop if the marks are less i wawnted to repeat it .
This is the code that i wrote
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
void mygrade(int grades)
{
if (grades >= 90)
{
printf("High distinction");
}
else if (grades > 80 < 70)
{
printf("Your Grade is Distinciton");
}
else if (grades > 60 < 70)
{
printf("Credit");
}
else if (grades > 50 < 60)
{
printf("Pass");
}
else if (grades < 50)
{
printf("Fail");
}
else
{
printf("Enter vaild Marks");
}
}
void main()
{
int grades;
printf("Enter your score for this unit\n");
scanf("%d", &grades);
printf("your grade for this unit is: %d ");
}
If you want the program work as you write in the picture, there are three things to do:
You can just use
if (grades >= 90)
// …
else if (grades >=80)
// …
// and so on
since else if statement will be trigger only if all cases above it are not true.
You need to call mygrade() function in the main() function so that it will run.
If you want to repeat the program if the grades are less than 50, then you can use do-while loop.
do
{
//…
}while (grades < 50);
Your mistake is to use comparisons like "(grades > 80 < 70)", which is not allowed in C++. Replace them with the form "((grades > 70) && (grades < 80))"

The Coursera autograder gives me Unknown Signal 11

I'm in a class in Algorithms and now we are taking Greedy Algorithms.
Two of my solutions output "Uknown Signal 11" on some of the test cases.
However, I drove my program to the limit with the largest inputs possible.
It works just fine on my PC. However on Coursera's grader, it throws tgghis cryptic message of Unknown Signal 11.
Will this go away if I change to Python for example?
Here's the first code exhibiting the problem:
#include <iostream>
#include <utility>
#include <algorithm>
using namespace std;
bool sortAlg(pair<double, pair<uint64_t,uint64_t>> item1, pair<double,
pair<uint64_t,uint64_t>> item2)
{
return (item1.first >= item2.first);
}
int main()
{
uint64_t n, index = 0;
double W, val;
cin >> n >> W;
pair<double, pair<uint64_t,uint64_t>> items[n];
for (int i=0; i <n; i++)
{
cin >> items[i].second.first >> items[i].second.second;
items[i].first = (double)items[i].second.first / (double)items[i].second.second;
}
sort(items,items+n, sortAlg);
while(W > 0 && n > 0)
{
if (items[index].second.second <= W)
{
val += items[index].second.first;
W -= items[index].second.second;
index++;
n--;
}
else
{
val += items[index].first * W;
W = 0;
index++;
n--;
}
}
printf("%.4f",val);
return 0;
}
I think this has to do with the while loop, but I can't think of anything where the program will make an out of bounds array call using index.
Anyways it is a fractional knapsack implementation.
Here's the second code which also gives unknown signal 11:
#include <iostream>
#include <string>
#include<vector>
#include <algorithm>
#include <utility>
using namespace std;
bool sortAlg(string num1, string num2)
{
if (num1[0] > num2[0]) return true;
else if (num1[0] < num2[0]) return false;
else
{
if (num1.size() == 1 && (num1[0] > num2[1])) return true;
else if (num1.size() == 1 && (num1[0] < num2[1])) return false;
else if (num2.size() == 1 && (num1[1] > num2[0])) return true;
else if (num2.size() == 1 && (num1[1] < num2[0])) return false;
else if (num1 == "1000" || num2 == "1000") return (num1 < num2);
else
{
if (num1.size() == num2.size()) return (num1 > num2);
else
{
return (num1[1] > num2[1]);
}
}
}
}
int main()
{
string num;
int n, n2 = 1;
cin >> n;
//int numbers[n];
vector<string> numbers2;
for (int i =0; i <n; i++)
{
num = to_string(n2);
cout << num << endl;
numbers2.push_back(num);
n2 += 10;
}
sort(numbers2.begin(), numbers2.end(), sortAlg);
for (auto number : numbers2)
{
cout << number;
}
return 0;
}
I suspect the sortAlg function used in sort function, but on my PC it is relatively fast. And the problem statement required some weird sorting.
The problem was given a set of numbers, arrange them to make thebiggest number possible.
If given 9, 98, 2, 23, 21 for example it should give me 99823221.
(9 > 98 > 23 > 2 > 21)
So I sort by the first digit then the next and so on.
You have a StackOverflow error.
The necessary stack size depends on the depth of your recursion, the number of parameters of your recursive function and on the number of local variables inside each recursive call.
In Python, you have to set the necessary stack size. The starter files provided in Python 3 would have the sample below:
import threading
sys.setrecursionlimit(10 ** 6) # max depth of recursion
threading.stack_size(2 ** 27) # new thread will get stack of such size
...
threading.Thread(target=main).start()
Note how the stack_size is allocated.
It's just an additional information related to Coursera grader.
In the week 6 the same course , if you declare a 2D array for the dynamic programming problem, the grader gives the Signal 11 error and program fails even if it is working perfectly fine on local machine .
Solution to above problem - replace 2-D array by 2D vector (in case of C++) and submit again. The grader will accept the code solution and no signal 11 error will be thrown.

How do I stop these if else statements from compounding?

I'm trying to write a c++ program that reads input from a text file and assigns grades using a ten point grading scale then prints the results onscreen.
I think my issue may be with the if else statements in the function deriveGrade, rather than incrementing the enum, they seem to be suming up the increments. Any help would be appreciated, thanks.
#include <iostream>
#include <string>
#include <iomanip>
#include <cmath>
#include <fstream>
using namespace std;
int deriveGrade(double avarage);
enum letter_grade { A, B, C, D, F };
namespace tenPoint
{
letter_grade deriveGrade(double avarage);
char grade;
}
using namespace tenPoint;
int main()
{
string name;
double average;
ifstream inData; // Is the variable for input data from the file.
inData.open("student_status.txt", ios::in);
while (!inData.eof())
{
getline(inData, name);
inData >> average;
inData.ignore();
grade = ::deriveGrade(average);
cout << name << " " << average << " " << char(grade) << endl;
}
inData.close();
return 0;
}
int deriveGrade(double average)
{
if (average >= 90)
{
grade = static_cast<letter_grade>(grade + 65);
}
else if (average >= 80 && average < 90)
{
grade = static_cast<letter_grade>(grade + 1);
}
else if (average >= 70 && average < 80)
{
grade = static_cast<letter_grade>(grade + 2);
}
else if (average >= 60 && average < 70)
{
grade = static_cast<letter_grade>(grade + 3);
}
else if (average <= 50)
{
grade = static_cast<letter_grade>(grade + 4);
}
else
{
cout << "Invalid entry." << endl;
}
return grade;
}
Input from file:
Doe, John K.
93.2
Andrews, Susan S.
84.7
Monroe, Marylin
75.1
Gaston, Arthur C.
62.8
Harpo, Joanie Y.
42.7
Ginger, Fred T.
95.8
Program output:
Doe, John K. 93.2 A
Andrews, Susan S. 84.7 B
Monroe, Marylin 75.1 D
Gaston, Arthur C. 62.8 G
Harpo, Joanie Y. 42.7 K
Ginger, Fred T. 95.8 î
Press any key to continue . . .
Logic of your program is quite strange, but some common remarks can be given without deepening into your task.
Pay attention, that while you use if... else statements one by one like
if (average >= 90)
{
grade = static_cast<letter_grade>(grade + 65);
}
else if (average >= 80 && average < 90)
{
grade = static_cast<letter_grade>(grade + 1);
}
...
there is no need to check average < 90 in the else branch after average >= 90 found false. So at least code can be shorter:
int deriveGrade(double average)
{
if (average >= 90)
{
grade = static_cast<letter_grade>(grade + 65);
}
else if (average >= 80)
{
grade = static_cast<letter_grade>(grade + 1);
}
else if (average >= 70)
{
grade = static_cast<letter_grade>(grade + 2);
}
else if (average >= 60)
{
grade = static_cast<letter_grade>(grade + 3);
}
else if (average <= 50)
{
grade = static_cast<letter_grade>(grade + 4);
}
else // check here! Invalid interval is for values between 50 and 60?
{
cout << "Invalid entry." << endl;
}
return grade;
}
But this is not significant improvement.... much better to make a formula and use single statement with assignment to grade = ...
UPDATE:
And one more comment. If you know the interval of unacceptable values, check it first (before all other calculations):
int deriveGrade(double average)
{
// check the correctness of argument first
if (average > 50 && average < 60)
{
cout << "Invalid entry." << endl; // notification
return grade; // previous value
// also consider returning special value for error case
}
// calculate value for grade
grade = ...
// return updated value
return grade;
}
section "calculate value for grade" is for you, and while writing this part of code keep in mind that:
ternary operation operation is useful for one special case, e.g. grade = (average >= 90)? 65 : floor(100 - average) / 10;
using global values (like grade) in a function is bad practice as well as making logic based on the assumption that initial value of global variable is correct
The reason is because you are adding to your grade variable without clearing it, so the result of previous operations are carried over in deriveGrade.
My advice is to remove the global char grade; in your namespace, use a local variable in your deriveGrade, and a different local variable in your main.
If you look at your function code, grade will only have 65 added to it (to make an ASCII 'A') if your grade is above 90. Every subsequent addition however, pretends that this addition has happened. If you instead make sure that each else if does not rely on previous if or else if code, then your code should be more correct.
char deriveGrade( double average )
if( average > 90.0 )
{
return 'A';
}
else if( average > 80.0 )
{
return 'B';
}
...
This solution removes even the need to use a grade variable in your deriveGrade
An even better alternative that uses the enum you so nicely created is:
enum letter_grade : char
{
A = 'A', B = 'B', C = 'C', D = 'D', F = 'F'
};
Which allows you through a (char)letter_grade to swap between the enum representation and a char (your deriveGrade would then return a letter_grade instead).

Why is my program crashing when I'm trying to fill up an array?

So with this program, basically, I ask for the names of three people, and store those strings in an array. That parts seems to work fine.
After that, I ask for their quarterly reports. So each person gets 4, and it's ordered through the array so that:
Index 0-3 goes to person A
Index 4-7 goes to person B
And index 8-11 goes to person C.
In this second for-loop that processes this second array, I have a list of if/else if statements that determine the name of the person in question that I will be asking for. In the separate function itself, readSales(), I have a similar thing set up to determine which quarter to ask for. This is designed to loop 12 times in order to get all 12 indexes filled.
For some reason, after I input the people's names, the program crashes. Any idea why?
Also, I know "using namespace std;" isn't very popular, but that's how my professor wants it so that's how I have it.
// In this program, I will
// (1) Ask for the names of three salespeople.
// (2) Accept sales for each quarter (for each person).
// (3) Display their name and total sales amount.
// I will use three functions:
// (1) main
// (2) readInfo
// (3) displayInfo
// No global variables, and I will pass data as parameters.
#include <iostream>
#include <string>
using namespace std;
// In order to pass an array through a void function,
// I must create it in the main function.
// So...
string readNames(int); // Function that gathers data from user.
double readSales(string, int);
void displayInfo(); // Function that displays final result.
int main() // Our main function
{
// Create my variables for arrays and final result.
string arrNames[3];
double arrSales[12], result;
// I must call my first function now.
for (int i = 0; i < 3; i++)
{
arrNames[i] = readNames(i); // Successfully gathers all 3 names and stores them in the array. Woo!
}
// Now I must gather the number data, using a double array.
string person = "uninitialized";
int x = 0;
for (x; x < 12; x++);
{
if (x < 4) // setup to ask question
person = arrNames[0];
if (x < 8)
person = arrNames[1];
if (x < 12)
person = arrNames[2];
arrSales[x] = readSales(person, x); // Successfully gathers all 12 quarters and stores them. Yay!
}
cout << arrNames[3];
} // end function main()
string readNames(int count)
{
for (count; count < 3;)
{
string i;
cout << "Please input salesperson " << count + 1 << "'s name: ";
cin >> i;
cout << endl;
return i;
}
return 0;
} // end function readNames()
double readSales(string person, int count) // reading the sales
{
double i; // variable I am returning at the end of function.
int quarter;
if (count == 0 || count == 4 || count == 8)
{
quarter = 1;
}
else if (count == 1 || count == 5 || count == 9)
{
quarter = 2;
}
else if (count == 2 || count == 6 || count == 10)
{
quarter = 3;
}
else if (count == 3 || count == 7 || count == 11)
{
quarter = 4;
}
else
return 0;
cout << "Please input salesperson " << person << "'s sales for Quarter " << quarter << " (Please round to the nearest cent): $" << endl;
cin >> i;
return i;
}
Please remove the semi-colon in the for (x; x < 12; x++);
You can make it like this,
int x = 0;
for (x; x < 12; x++)
{
if ((x >= 0) && ( x <= 3)) // setup to ask question
{
person = arrNames[0];
}
else if ((x >= 4) && (x <= 7))
{
person = arrNames[1];
}
else
{
person = arrNames[2];
}
arrSales[x] = readSales(person, x); // Successfully gathers all 12 quarters and stores them. Yay!
}

If statements in c++ doubles

#include <iostream>
#include <windows.h>
#include <cstdlib>
#include <stdlib.h>
using namespace std;
int main()
{
int x,y,z;
cout<<"welcome to guessing game\nplayer one pick your number: ";
cin>>x;
if (x < 0)(x > 100);
{
cout<<"out of number range";
}
Sleep(2000);
system("cls");
cout<<"ok player 2 pick the guess";
cin>>y;
if (x == y){
cout<<"congrats you got it right";
}
else{
if (x < y){
cout<<"Go lower";}
else {
if (x > y){
cout<<"higher";}}
}
system("pause>nul");
return 0;
}
i cant see the get the initial if statement to work no matter what number i type in it would auto display the out of number range. also am i allowed to place the conditions like that soo close like if (x < 0)(x > 100);. also how do i make it soo it returns to the start of the program?
There is an error:
if (x < 0)(x > 100);
{
cout<<"out of number range";
}
Should be:
if (x < 0 || x > 100)
{
cout<<"out of number range";
}
You also need to work on your indentation; those if/else statements towards the bottom look dodgy (I cannot really tell due to the indentation).
Aside from writing if (x < 0 || x > 100) (and dropping the semicolon), you should be wary of comparing equality on floating point. I would red flag your line if (x == y){ if reviewing your code.
See Floating point comparison
nobody else is actually answering your second question: how to loop it, here you go:
int x;
cout << "Welcome to the guessing game\n";
do {
cout << "Please enter a number from 0 to 100: ";
cin >> x;
} while (x < 0 || x > 100);
You have written
if (x < 0)(x > 100);
{
cout<<"out of number range";
}
First remove the semi colon.
Second did you mean
if ((x < 0) || (x > 100))
{
cout<<"out of number range";
}
try this:
/*
if (x < 0)(x > 100);
{
cout<<"out of number range";
}
*/
if (x < 0 || x > 100)
{
cout<<"out of number range";
}
There are a few notable syntax errors:
if (x < 0)(x > 100);
{
cout<<"out of number range";
}
First of all, you can't just put two conditions side by side like that in C++ that I know of. You'd have to separate them with || for OR, or && for AND (in most cases - there are some others).
Also, you had a ; at the end of your if statement. I believe that doing this in C++ will result in some problems too.
Your final code should look like:
if ((x < 0) || (x > 100))
{
cout << "out of number range" << endl;
}
The << endl; part is optional. This adds a new line to your output, for more readability next time you write something.
Also, to loop your entire game repeatedly, I would use a do-while loop. You can learn about them here.