Error while using If else - dev-c++

I'm trying to create a program that you need to enter 3 numbers and needs to tell you which one is greater, and I'm getting the error:[Error] expected '(' before 'else'.
The error is in line 17 and 21.
Here is the code.
using namespace std;
int main(){
int n1, n2, n3;
cout<<"Type 3 numbers : ";
cin>>n1>>n2>>n3;
if (n1 > n2 && n1 > n3){
cout<<"The graeter is : "<<n1;
}
if else{
(n2 > n3);
cout<<"The graeter is: "<<n2;
}
if else {
cout<<"The graeter is: "<<n3;
}
return 0;
}

You've put if else where it should be else if. You also put the condition inside the code block. In your final test, you only else because there is no other alternative beyond this. Try this:
int main()
{
int n1, n2, n3;
cout<<"Type 3 numbers : ";
cin>>n1>>n2>>n3;
if (n1 > n2 && n1 > n3) {
cout<<"The greater is : "<<n1;
}
else if (n2 > n3) {
cout<<"The greater is: "<<n2;
}
else {
cout<<"The greater is: "<<n3;
}
return 0;
}
I can't run it at the moment, so there may be other errors I haven't spotted.
Some programmers recommend putting brackets in to ensure your intention is explicit (see the Dangling Else Problem) but in this case it isn't necessary.

Related

C++ Gapful Numbers Crashing

I was doing this program in which I am supossed to print gapful numbers all the way up to a specific value. The operations are correct, however, for some reason after printing a couple of values the program crashes, what can I do to fix this problem?
Here's my code:
#include<math.h>
#include<stdlib.h>
using namespace std;
void gapful(int);
bool gapCheck(int);
int main(){
int n;
cout<<"Enter a top number: ";
cin>>n;
gapful(n);
system("pause");
return 0;
}
void gapful(int og){
for(int i=0; i<=og; i++){
fflush(stdin);
if(gapCheck(i)){
cout<<i<<" ";
}
}
}
bool gapCheck(int n){
int digits=0;
int n_save,n1,n2,n3;
if(n<100){
return false;
}
else{
n_save=n;
while(n>10){
n/=10;
digits++;
}
digits++;
n=n_save;
n1=n/pow(10, digits);
n2=n%10;
n3=n1*10 + n2;
if(n%n3 == 0){
return true;
}
else{
return false;
}
}
}
I'm open to any suggestions and comments, thank you. :)
For n == 110, you compute digits == 3. Then n1 == 110 / 1000 == 0, n2 == 110 % 10 == 0, n3 == 0*10 + 0 == 0, and finally n%n3 exhibits undefined behavior by way of division by zero.
You would benefit from more functions. Breaking things down into minimal blocks of code which represent a single purpose makes debugging code much easier. You need to ask yourself, what is a gapful number. It is a number that is evenly divisible by its first and last digit. So, what do we need to solve this?
We need to know how many digits a number has.
We need to know the first digit and the last digit of the number.
So start out by creating a function to resolve those problems. Then, you would have an easier time figuring out the final solution.
#include<math.h>
#include <iostream>
using namespace std;
void gapful(int);
bool gapCheck(int);
int getDigits(int);
int digitAt(int,int);
int main(){
int n;
cout<<"Enter a top number: " << endl;
cin>>n;
gapful(n);
return 0;
}
void gapful(int og){
for(int i=1; i<=og; ++i){
if(gapCheck(i)){
cout<<i << '-' <<endl;
}
}
}
int getDigits(int number) {
int digitCount = 0;
while (number >= 10) {
++digitCount;
number /= 10;
}
return ++digitCount;
}
int digitAt(int number,int digit) {
int numOfDigits = getDigits(number);
int curDigit = 0;
if (digit >=1 && digit <= numOfDigits) { //Verify digit is in range
while (numOfDigits != digit) { //Count back to the digit requested
number /=10;
numOfDigits -=1;
}
curDigit = number%10; //Get the current digit to be returned.
} else {
throw "Digit requested is out of range!";
}
return curDigit;
}
bool gapCheck(int n){
int digitsN = getDigits(n);
if (digitsN < 3) { //Return false if less than 3 digits. Single digits do not apply and doubles result in themselves.
return false;
}
int first = digitAt(n,1) * 10; //Get the first number in the 10s place
int second = digitAt(n,digitsN); //Get the second number
int total = first + second; //Add them
return n % total == 0; //Return whether it evenly divides
}

How to Exit program loop on pressing Enter/Return Key in C++?

The Challenge is Given like this:
You are provided with an unknown number of test cases. Each test case consists of a natural number, which is followed by a white space, relational operator (==, !=, >= or <=), white space, and another natural number. All test cases are separated with a new line character. You can assume that no number has more than 1000 digits.
So, I'm trying to solve the above problem using C++.The problem is, this program should run for any number of cases that will be checked by Online Judge but my code is works for a limited number of inputs only, as the code will going to be checked by online judge and number of inputs is not specified. So I stuck how to solve this problem.I also tried using do..while() loop and while() loop but it doesn't work -_-
My code is given below:
#include <iostream>
using namespace std;
bool isSmaller(int n1, int n2, string oper)
{
// Calculate lengths of both string
if (oper == "==")
/* code */
if (n1 == n2)
return true;
if (oper == "<=")
/* code */
if (n1 <= n2)
return true;
if (oper == ">=")
/* code */
if (n1 >= n2)
return true;
if (oper == "!=")
/* code */
if (n1 != n2)
return true;
return false;
};
int main() {
/* code */
int n1, n2;
string oper;
for (int i = 0; i < 1; i++) {
cin >>n1>>oper>>n2;
}
for (int j = 0; j < 1; j++) {
if(isSmaller(n1, n2, oper)){
std::cout <<1<<'\n';
}
else{
std::cout <<0<< '\n';
}
}
return 0;
}
Ideal OUTPUT:
A binary sequence should appear on the output. ith element of the sequence should be equal to 1 or 0, depending on whether the corresponding relation is true or false. All elements of the sequence should be separated with a new line character.
Example
Input:
100 == 200
200 <= 100
200 >= 100
Output:
0
0
1
Here scanf() will help you to take unknown number of inputs.
You can include or to use scanf() and printf() in your C++ program.
while(scanf("%d %s %d",&n1,oper,&n2) == 3)
{
//Your code goes here.
}
Explanation
This works because scanf() returns the total number of inputs scanned successfully, or EOF if input failure occurs before the first receiving argument was assigned.
And in this case it will return 3 as for a successful scanning of n1, oper and n2.
finally I wrote the code based on the hint given by #bruno but still online judge returns an error I don't know wheres the problem but the code seems correct.
The Code is Below:
#include <iostream>
#include <iomanip>
#include <sstream>
#include <list>
using namespace std;
bool computeResult(string line)
{
// compare two values from given operator
istringstream stream(line);
int n1, n2;
string oper;
stream >> n1 >> oper >> n2;
stream >> std::cout.rdbuf();
if (oper == "==")
return (n1 == n2);
if (oper == "!=")
return (n1 != n2);
if (oper == ">=")
return (n1 >= n2);
if (oper == "<=")
return (n1 <= n2);
return false;
};
int main() {
/* code */
list<bool> result;
std::string line;
std::istringstream stream(line);
cout << "Enter Numbers \n";
std::getline(std::cin, line);
do {
result.push_back(computeResult(line));
} while(std::getline(std::cin, line) && !line.empty());
for (auto b : result)
std::cout << b << std::endl;
return 0;
}

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.

highest cf between 2 numbers c++

This is a program to find highest common factor:
#include <iostream>
enter code here using namespace std;
void main ()
{
int max=0 , min=0 , x,y,hcf=0;
cout<<"enter 2 numbers\n";
cin>>x>>y;
if (x>y)
{
max=x;
min=y;
}
else if (y>x)
{
max=y;
min=x;
}
if
(max%min==0)
{ hcf=min;
cout<<"highest cf is:"<<hcf<<endl;}
else
{
hcf=min;
do
{
hcf--;
}
while (max%hcf!=0 && min%hcf!=0);
cout<<"highest cf is:"<<hcf<<endl;
}
system ("pause");
}
although when i test it ; it takes the condition max% hcf !=0 and ignores the second one ... for example if i input 12 and 8 then 12 is called max and 8 is min then it outputs 6 as hcf
that means it ignored the second condition ... as i understand of course.
so where is my mistake ?
A easy solution to get the HCF is to do this.
int HCF(int num1, int num2)
{
for(int i = num1; i > 2; i++)
{
if(num1 % i == 0 && num2 % i == 0) return i;
}
return 1;
}

logical error in perfect number program

I was wondering how to develop a C++ program that prompts the user for 2 numbers n1, n2 with n2 being greater than n1. Then the program is meant to determine all the perfect numbers between n1 and n2. An integer is said to be a perfect number if the sum of its factors, including 1 (but not the number itself), is equal to the number itself. For example, 6 is a perfect number because 6 = 1 + 2 + 3.
so far here is what I have come up with, and it has no runtime/syntax errors, but unfortunately logical error(s):
#include <iostream>
using namespace std;
int main(){
int number, sum = 0, divi = 1, n1, n2;
cout<<" Please enter n1: ";
cin>>n1;
cout<<" Please enter n2: ";
cin>>n2;
number = n1;
while(number <= n2){
while(divi <=n2){
if (number%divi ==0)
sum+=divi;
divi++;
}
if(sum == number)
cout<<number<<endl;
number++;
}
return 0;
}
I can only use while loops. Can you spot any logical errors?
You need to reset divi to 1 and sum to 0 just after the line while(number <= n2){. (Otherwise divi and sum will grow in error).
Redefine the upper bound of your inner while to while(divi < number){. (You want to examine the factors between 1 and number, not after it.)
#include <iostream>
using namespace std;
int main(){
int number, sum = 0, divi = 1, n1, n2;
cout<<" Please enter n1: ";
cin>>n1;
cout<<" Please enter n2: ";
cin>>n2;
number = n1;
while(number <= n2){
sum=0; // reintialize variable for every incrasing number n1 to n2
divi=1; // reintialize variable
while(divi <number){ //use number insteaed of n2
if (number%divi ==0)
{
sum+=divi;
}
divi++;
}
if(sum == number)
cout<<number<<endl;
number++;
}
return 0;
}