The teacher said that whenever the c variable is negative then: "the variable a is negative", but this doesn't make sense.
Is the program written in the wrong form?
In my opinion else should be part of the if(a>0) with {}. I don t know why he chose to not use it.
In conclusion, is the correct form like: if(a>0){...}else and than cout?
#include <iostream>`
using namespace std;
int main(void) {
int a, b, c;
cin >> a;
cin >> b;
cin >> c;
if (a > 0)
if (b > 0)
if (c > 0)
cout << "they are all positive";
else
cout << "the number a is negative";
}
Your teacher is correct. else applies to the newest if, so the value of c determines the output. (More specifically, the program will only print something when both a and b are positive.) You can test this by running the program.
The output "the number a is negative" is illogical, because that's the point of the test. The program is intentionally written incorrectly. If answers to all test questions were obvious, everybody would get the best grade.
You need to use curly brackets otherwise else will only apply to the newest if. The program will only print when both a and b are positive.
The core problem here is the lack of a clear specification of what the program is supposed to do. I suspect that you do have it, but without it available here I can only explain what the code is doing and how the quote from the teacher can be read as describing what the code does.
To visualise here is a modified version of your code, which is self-explaining (I hope):
#include <iostream>
using namespace std;
int main(void) {
int a, b, c;
cin >> a;
cin >> b;
cin >> c;
if (a > 0)
if (b > 0)
if (c > 0)
cout << "they are all positive"; // true
else
cout << "the number 'c' is negative or zero, 'a' and 'b' are positive";
else
cout << "the number 'b' is negative or zero , 'a' is positive, no idea about 'c'";
else
cout << "the number 'a' is negative or zero , no idea about 'b' and 'c'";
}
I suspect that where this outputs "no idea" is where you might want to use more ifs, in order to describe the other numbers.
Note: I stuck to your style (without {}). But I recommend to use them generously. In my experience it makes life easier and in my opinion makes code more readable.
I think the quote from the teacher
whenever the c value is negative it say: " the a number is negative" but it doesn't make sense
Should be read as:
'Whenever the c value is negative (and the other two are positive) this code outputs: "the 'a' number is negative", but that doesn't make sense, because a is in fact positive when this output occurs.
And I agree.
Related
I have been learning c++ recently. When I tried to run the following lines...
#include <iostream>
short a = 0;
short b = 1;
short c, i;
void Fibonacci(){
std::cout << a;
std::cout << b;
while (a <= 100){
c = a + b;
a = b;
b = c;
std::cout << c;
}
}
int prime_number(short a){
if (a == 1){
std::cout << "It's a prime number\n";
} else{
for (i = 2; i < a; i++){
if ((a%i) == 0){
std::cout << "It's a prime number\n";
std::cout << "The given number is divisible by " << i << "\n";
return 0;
}
}
std::cout << "It's not an prime number";
}
}
int main(){
short user_input;
std::cout << "Press 1 for Fibonacci and 2 for prime number";
std::cin >> user_input;
if (user_input == 1){
Fibonacci();
}
if (user_input == 2){
std::cout << "Type the number to check whether it's prime";
std::cin >> a ;
prime_number(a);
}
}
...I get an error saying:
In function ‘int prime_number(short int)’:
Function.cpp:37:1: warning: control reaches end of non-void function [-Wreturn-type]
37 | }
I searched various platforms for the answers, but I couldn't understand what really happens here. It's an error because the compiler cannot find whether the function has an end or not. Can someone help me understand the error and solve it?
Warnings aren't errors. When you compile a program and only get warnings (ie. no errors) then this means your program has successfully compiled (an executable has been made). When you get errors, this means that compilation was aborted (so no executable output - if you already had one, it won't have been updated).
It's warning you that when the integer input is 1 that you aren't specifying a return — which is invalid. Also, if it's not 1, then the the else statement still doesn't guarantee a returned value:
for (i = 2; i < a; i++){
if ((a%i) == 0){
std::cout << "it's a prime number\n";
std::cout << "The given number is divisible by " << i << "\n";
return 0;
}
}
The compiler can't know that return 0 will always be executed here - and even if it could, the compiler isn't designed to always understand the logic of your code. Even knowing your logic, return 0 will only be executed if a is greater than 2 and non-prime.
You could fix this by putting return statements in both of your if statements, or even at the end of your function. But notice that you never use the return value? This implies that your prime_number() function should be void prime_number(), then you won't need return values at all, and can just use break; in your loop - or return; if you prefer (here's an example of how to resolve this particular issue - there's still other bugs though, discussed below).
This is probably confusing to a beginner: Why doesn't it warn you when the function int main() contains no return value? This is because main is special: If no return value is given, it implies return 0.
Another thing that may confuse you here is if you ever compile with the flag -Werror. If you do, then the original code will give you an error, because the Werror flag turns all warnings into errors (to force programmers to pay attention to the warnings).
The logic of your code isn't right - it's actually the opposite: 1 is defined as not a prime number (this is because of the value we get from unique prime decomposition, so mathematicians chose to exclude 1 as prime). Also, ((a%i) == 0) means that when a is divided by i that it has 0 remainder, ie. i divides a, so a is not prime.
Finally, avoid using global variables. Keep all your variables local so that the logic of your code is simpler (easier to read / less bug-prone).
Here's an example of how you could rewrite your code that resolves all the above issues.
As Elliott in the comments has said the warning you are getting is not going to affect your program at all. It's recommend that you return something since you function has a return type of integer.
Below is a easy fix to get rid of the warning. :)
Old Code:
if (a == 1)
{
std::cout << "Its a prime number\n";
}
New Code without the Warning:
if (a == 1)
{
std::cout << "Its a prime number\n";
return 0;
}
I have recently started to program in C++ and i wrote a simple file to try and test. It converts Celsius to Fahrenheit and vice versa. It keeps giving me an error about expecting a 'while', and a '('
As i said I'm new to this and really don't know what to try. I've moved the if else and else onto the same line as the ending curly brace, of the former if/if else statement.
#include <iostream>
int main()
{
int f;
int c;
char choice;
ask:do {
std::cout << "Hello welcome! Would you like to convert from C to F (a) or F to C (b)?\n";
std::cin >> choice;
}
if (choice == "a") { // that if before this comment has squiggly red line
std::cout << "Great, What is the temperature in Celcius? (No decimals please)\n";
std::cin >> c;
f = (c * 1.8) + 32;
std::cout << "The temp in Farenheight is " << f << "degrees\n";
}
if else (choice == "b") {
std::cout << "Great, What is the temperature in Celcius? (No decimals please)\n";
std::cin >> c;
c = (f / 1.8) - 32;
std::cout << "The temp in Celsius is " << c << "degrees\n";
}
else {
std::cout << "Sorry that wasn't an option. Please try again.";
goto ask;
}
} // this also is squiggly
I would like it to output the number of c to f vice versa, but it wont run and it says:
expected a 'while' 18 ,5
expected a '(' 42 ,1
The code here has a syntax error:
do {
std::cout << "Hello welcome! Would you like to convert from C to F (a) or F to C (b)?\n";
std::cin >> choice;
}
The do keyword needs to be paired with a while, as the loop is do ... while rather than just do. So, for example, you might say something like
do {
std::cout << "Hello welcome! Would you like to convert from C to F (a) or F to C (b)?\n";
std::cin >> choice;
} while (!isValidInput(choice));
where isValidInput would be some helper function that validates the input.
So in other words, the issue isn't that you can't use an if statement here as much as your do ... while loop is incomplete.
There are some other syntax errors here as well. For example, you can't say if else, though else if is perfectly fine. Another issue: in C++, double-quotes are used for strings while single-quotes are used for characters, so comparisons of the form choice == "b" won't compile, because you're comparing a char and a string. Those errors will likely surface after you fix the aforementioned one.
As a final note, while goto is indeed legal in C++, it's generally frowned upon in favor of other options like regular styles of loop. If you follow the above approach of having your loop continue until you get a valid input, then you should be able to eliminate the goto that takes you back to the point where you ask for input.
Hope this helps!
The do is a loop in c++. Specifically it is part of the do … while loop. It expects you to clarify how long the loop should be executed until the condition is met (and the do... while loop is different from while loop in that it executes the code at least once no matter what).
A ///
Your do is not enclosing your entire program in curly braces, so if you're not trying to loop your entire program then you may not need do at all. Simply make it
std::cout << "Hello welcome! Would you like to convert from C to F (a) or F to C (b)?\n";
std::cin >> choice;
B ///
If you want to loop the entire program the curly braces after do must capture everything and be finished with a while. In this scenario you can remove your goto statement; this answer can explain why you may want to avoid this What is wrong with using goto?.
E.g.
bool loop = true;
do {
// your program
} while (loop); // this will loop while "loop" variable continues to be true
You can then have a condition in your loop somewhere that changes loop = false to break the loop, for example asking the user if they want to continue or not.
///
Some other things I noticed about your code:
char is assigned values with ' and note ".
if else is not correct, instead it is else if (…
I'm very very new to C++. Here I'm trying to write a program without any extra library. Using loops to find both the smallest value and the second smallest value from the user's inputs ( 0 is excluded and exits the program ).
Here is what I tried to do.
#include <iostream>
using namespace std;
int main()
{
int value=0;
int SmallestNumber=0;
int SmallestNumber2=0;
cout << "Enter number to find the smallest and second smallest(or 0 to exit): ";
cin >> value;
while (value != 0) {
if (value< SmallestNumber && value != 0 )
{
SmallestNumber = value;
}
else if (value<SmallestNumber && SmallestNumber2 >SmallestNumber && value != 0)
{
SmallestNumber2 = value;
}
cout << "Enter number to find the smallest and second smallest(or 0 to quit): ";
cin >> value;
}
cout << "Smallest number is: " << SmallestNumber << '\n' << endl;
cout << "Second Smallest number is: " << SmallestNumber2 << '\n' << endl;
return 0;
}
However, this program is not functioning properly. The smallest number finder works only if I input a negative value **, and the second smallest number value always outputs **0.
Since I'm very new to C++, I tried many other solutions, but this is what I can really think of.
Can somebody please tell me what is wrong with the program, and how I can correct it?
A million thanks! Please help me :'(
Thanks for answering my question!
I changed the initialization into this.
int value;
int SmallestNumber=0;
int SmallestNumber2=0;
but how do I initialize the smallest and the second smallest values..?
This is what I wanted my program to do
displaying the smallest and second smallest
50
1
61
93
-35
38
0
-35 smallest
1 second smallest
You start with a smallest value set to 0, so you will always get values only smaller than 0, that's why you have std::numeric_limits<int>::max().
Then for your second smallest, you are never checking against the current second smallest value, you are just checking against the biggest, which you now is going to work. So change this:
if (value>SmallestNumber2 && value != 0)
You should probably check value != 0 outside the main if statements as well. And as #Caleb reminded me, what happens to the previous largest value if it gets replaced?
Also, if you want to keep the same concept and do the algorithm "yourself" there is few things to change.
First the initial value of SmallestNumber and SmallestNumber2 need to be as high as possible otherwise the numbers saved can only be the one lower than your initial value. Therefore you can use INT_MAX.
Second, the second smallest number, need to be set in 2 cases :
when a new value is entered that is the second smallest
when a new smallest value is set, the old smallest value become the new second smallest.
Third there are a lot of unnecessary code here. You check too many time if value is not null which you know from the while condition. And you have code duplication with the cout/cin statement. Which is prone to mistakes.
Here is a version of what it could look like :
int value= INT_MAX;
int SmallestNumber=INT_MAX;
int SmallestNumber2=INT_MAX;
while (value != 0) {
if(value > SmallestNumber && value < SmallestNumber2)
{
SmallestNumber2 = value;
}
else if (value< SmallestNumber)
{
SmallestNumber2 = SmallestNumber;
SmallestNumber = value;
}
cout << "Enter number to find the smallest and second smallest(or 0 to quit): ";
cin >> value;
}
cout << "Smallest number is: " << SmallestNumber << '\n' << endl;
cout << "Second Smallest number is: " << SmallestNumber2 << '\n' << endl;
return 0;
ps : the version of #darune is a nicer solution.
You have no position at which the former smallest value becomes the second smallest value, which can't work.
Consider this code:
int value;
int smallest = std::numeric_limits<int>::max()-1;
int second_smallest = std::numeric_limits<int>::max();
while(true)
{
cin >> value;
if(value == 0) break;
if(value >= second_smallest) continue;
if(value == smallest) continue; // assuming that a double value does not change anything
if(value > smallest) // is between them
{
second_smallest = value;
continue;
}
//now the case left is that the new value is the smallest
second_smallest = smallest;
smallest = value;
}
Basic idea: first of all, rule out things and from then on, assume that they do not hold. We begin with the break case (I prefer a while(true) in such cases to have manual control over breaking it inside). Then we rule out the case in which nothing happens. The two cases left are that we are between the old values and that we are below both, and we handle them accordingly.
In your code, your ifs get to bloated. Makes it hard to keep track of what is done and what is to be done.
One example of this is that you have several times && value != 0 in your code despite this always being true due to the condition of your while.
In general, you should really learn how to use a debugger, or at least how to use helpful messages for debugging. Your mistake of setting your variables to zero at the start would have been easy to detect.
Other minor things: You should decide for a style and stick to it. It is quite unusual to name variables with a major first letter. Camel case is fine though, smallestNumber would have been fine. Second, try to avoid using namespace std;. This can lead to collissions. Rather use single members of std, like using std::cout;. It is not that problematic in a source file (very problematic in a header) but I recommend to do it consistently to keep a good routine.
A thing left to do in the code would be to later catch if the variables are still at std::numeric_limits<int>::max() and that minus one, signalling that there was no user input, and printing a fitting message instead of those values.
Note that as you read in an integer, negative values are legal, which might not be what you want, given that you use zero to break. You might want to add a case
if(value < 0)
{
cout << "Value was ignored due to being negative" << endl;
}
This is relatively simpel by using a a few different concepts, namely stdvector, stdstream and last stdsort
First off, the input part can be simplified to:
std::vector<int> numbers;
std::cout << "Enter multiple numbers, separated by spaces: ";
std::getline(std::cin, line);
std::istringstream stream(line);
while (stream >> number) {
numbers.push_back(number);
}
Now, since you would like the 2 smallest numbers, my suggested method would be to simply sort the vector at this point:
std::sort(numbers.begin(), numbers.end());
Now the list of numbers are sorted in ascending order and it is matter of printing the 2 first values. I leave that as an exercise to you.
I am writing a program to find a 4-digit address. The program should continually allow the user to enter digits until the correct answer is solved. Additional parameters are:
All four digits are different
The digit in the thousands place is three times the digit in the tens
place
The number is odd
The sum of the digits is 27
With the program I've written so far it gives me the same output of "address is correct" no matter the input is. Trying to figure out what I am doing wrong, but no success. This is the code I've written so far.
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int main()
{
int const Address = 9837;
int input;
char Y;
char N;
int sum;
int even;
int i;
cout << "Please enter a 4-digit number." << endl;
cin >> input;
{
while (input = Y || N)
{
if (input = Y)
cout << "Please enter a 4-digit number" << endl;
else if (input = N)
cout << "Good Bye!!" << endl;
return 0;
}
while (input != Address && Y && N)
{
if (sum = input == !27);
cout << "Not a valid address - the sum of the digits is not 27" << endl;
if (input % 2 == 0)
cout << "Not a valid address - the number is even." << endl;
}
input = Address;
cout << "Address is correct." << endl;
}
}
You include <cmath> and <string> but you don't use anything from that headers.
Declare/define variables as close to where they're used/needed.
You are using the variables N and Y uninitialized. They contain an indeterminate value (=garbage). If char happens to be unsigned, reading an indeterminate value (an uninitialized (unsigned) char) under a few certain conditions is allowed. But you use N and Y in a way where reading their values causes undefined behaviour.
The variables even and i are never used.
With cin >> input; you try to extract an integer from standard input. If the user would enter Y or N or anything else that is not an integer, extraction would fail. You need two different ways to get the users input: 1 to let the user enter his guessed number and 1 to let the user choose if he wants to play again.
You introduce a block ({) after cin >> input; that serves no purpose.
while (input = Y || N) ... Comparison is done with the operator == in C++ (and C) but = is assignment. The expression input = Y || N assigns the result of Y || N to input but since Y and N are uninitialized and chances that both contain the value 0 is quite low (0 || 0 would evaluate to false), input will almost always be 1 (true converted to an int is 1) and the loop will always execute.
Actually, reading the values of Y and N causes undefined behaviour because they're uninitialized. Theoretically (since the compiler knows that Y and N have indeterminate value), it can generate any code it likes.
Within the first while-loop:
if (input = Y) // is again an assignment, not a test for equality
cout << "Please enter a 4-digit number" << endl;
else if (input = N) // again
cout << "Good Bye!!" << endl;
return 0; // will always exit the program, no matter the value of input
In case all hell breaks loose and N and Y are both 0 by chance and thus the 2nd while-loop is reached, it is sure, that input is 0 (because otherwise the controlled statement of the 1st while-loop would have been executed and exited the program by return 0;). When input equals 0 it isn't equal to Address so input != Address yields true but since we know that N and Y are 0 (false) and true && false gives false, the controlled statement of the 2nd while-loop doesn't get executed.
I'll skip the contents of the controlled statement of the 2nd while-loop. Sufficive to say, they don't do what you think they do.
input = Address; // that assignment serves no purpose
cout << "Address is correct." << endl;
is the output you always get when the variables Y and N are 0, which might happen (especially when running debug-code).
Please, stay away from the source you're currently learning C++ from. Get a good textbook and start over.
Is the piece of code you have captured here missing something or incomplete? I see that Y, N and sum are not assigned any value and thus all conditions checks fail... Eventually it will display "Address is correct" always...
Remember that = and == are totally different.
= means an assignment. eg: int x = 100; means put the value of 100 into the variable x.
== means comparison or (is equal to). eg: if (x == 100), means if x has the value 100.
Also, If you're trying to make a choice variable for Yes or No,
You should do it this way:
char ans;
if (ans == 'Y' || ans == 'N")
Since your input variable is an int, and your choice variable is a char, your while statement is not valid.
A few things you need to know:
You should assign values to things before calling them
You should read about the difference between = and ==
If you want multiple inputs, your cin >> input; should be in your while loop
Your code is not well indented at some places
You are declaring a i integer, but you are never using it.
In other words: your compiler must be giving you a LOT of warnings. Did you look at them?
I'm still very new to C++ still and decided to make a fibonacci sequence. It worked (Woo!) but it doesn't work as well as I would like it to.
what I mean by that is say for example I told my program to count the first 10 terms of the sequence I will get
"0, 1, 1" and then I have to press enter for each additional number until it hits ten in which case the program returns 0 and ends.
How do I get the program to display all the numbers I want to without hitting enter for each additional one?
Here is my script:
#include <iostream>
using namespace std;
int main()
{
int FibNum;
cout << "How many numbers of the Fibonacci Sequence would you like to see? \n\n";
cin>> FibNum;
cin.ignore();
int a = 0;
int b = 1;
int c = 2;
cout << "Fibonacci Sequence up to " << FibNum << " terms.\n\n";
cout << a << "\n" << b << "\n";
for (int c = 2; c < FibNum; c++) {
int d = a + b;
cout << d;
cin.ignore();
a = b;
b = d;
}
}
Thanks in advance for any help!
P.s. Also if you notice anything terrible I'm doing please feel free to correct me, I'm very aware I'm probably doing a lot wrong, I'm just trying to learn. :]
A few things:
1) Remove int c = 2; as you're re-defining c inside the for loop.
2) Drop the line cin.ignore();: in your for loop: that will fix your "enter" problem; that line waits for some input then ignores it.
3) Put some white space in your output: e.g. cout << d << ' ' so your numbers are separated.
4) [Acknowledge vincent_zhang] Consider moving to uint64_t as your data type for a, b, and d. This is a standard type in C++11. It's a 64 bit unsigned integer type; adequate for a large number of terms.
and a small thing, bordering on personal opinion,
5) Use ++c instead of c++ as the former will never run slower as, conceptually at least, post-increment has to take a copy of the original value.
Besides the previous answers,
To better format the output, add white space by changing this
cout << d;
to
cout << d << " ";
You may want to change the type of a, b and d from int to double to prevent overflow.
(If you let FibNum=100 in your code, you should be able to observe overflow, meaning that you are going to get some incorrect numbers toward the end of the sequence.)
Move cin.ignore() out of the loop then you dont need to enter to print all the 10 numbers of Fibonacci series