I'm a beginner to learning C++. Just today I tried to learn the boolean operator and if-else statement.
This is the code:
int main(){
//if-else statement
int a, b;
bool result = (a < b);
std::cout << "input number 1 : ";
std::cin >> a;
std::cout << "input number 2 : ";
std::cin >> b;
std::cout << std::boolalpha << result <<std::endl;
if(result == true){
std::cout << a << " is less than " << b << std::endl;
}
if(!(result == true)){
std::cout << a << " is NOT less than " << b << std::endl;
}
return 0;
}
These are the results after a few executions:
Initially the results were fine, but then after a couple times it went wrong.
Does anybody know what the cause of this is?
Your mistake is that you compare the two variables and save the result before you assign any proper values to these variables. In other words, you compare uninitialized variables a and b which have undefined values.
First, you do:
bool result = (a < b);
And then after you get the values:
std::cin >> a;
std::cin >> b;
You should do the following instead:
// ...
int a, b;
std::cout << "input number 1 : ";
std::cin >> a;
std::cout << "input number 2 : ";
std::cin >> b;
bool result = a < b; // <-- move this down here!
// ...
You expect result to be evaluate a == b when you use it later. Instead bool result = (a < b); initializes result with (a < b) once and its value does not change afterwards. As neither a nor b are initialized when you declare result your code has undefined behavior.
You can make result a function object to make it work as you expected by using a lambda expression. However, to call it you'll have to add ():
int main(){
//if-else statement
int a = 0;
int b = 0;
auto result = [&](){ return a < b; };
std::cout << "input number 1 : ";
std::cin >> a;
std::cout << "input number 2 : ";
std::cin >> b;
std::cout << std::boolalpha << result() <<std::endl;
if(result()) {
std::cout << a << " is less than " << b << std::endl;
} else {
std::cout << a << " is NOT less than " << b << std::endl;
}
}
You should always initialize variables. Using the value of uninitialized variables is undefined behavior and can happen easily (as in your code) when you do not initialize variables. Instead of if (condition) {} if (!condition){} you can use if (condition) {} else {}. Instead of if (result() == true) you can write if (result()). And return 0; is implicit in main, you need not write it.
You overall code as it should be.
Explanations in the comments:
int main() {
//if-else statement
int a, b;
std::cout << "input number 1 : ";
std::cin >> a;
std::cout << "input number 2 : ";
std::cin >> b;
bool result = (a < b); // put this here, because now a and b have
// determined values
std::cout << std::boolalpha << result << std::endl;
if (result) { // or simple if (a < b) and drop result alltogether
std::cout << a << " is less than " << b << std::endl;
}
else { // no need for testing the opposite of result
std::cout << a << " is NOT less than " << b << std::endl;
}
return 0;
}
Related
So I did the next exercise, just with while loop:
Write a program that prompts the user for two integers.
Print each number in the range specified by those two integers.
Here is the code:
#include <iostream>
int main()
{
std::cout << "Write two numbers: " << std::endl;
int v1 = 0, v2 = 0;
std::cin >> v1 >> v2;
std::cout << "The numbers between " << v1 << " and " << v2 << " are: " << std::endl;
while (v2 < v1 && ++v2 < v1)
{
std::cout << v2 << std::endl;
}
while (v1 < v2 && ++v1 < v2)
{
std::cout << v1 << std::endl;
}
}
Now I have to do it with the for loop, which I did like this:
#include <iostream>
int main()
{
std::cout << "Write two numbers: " << std::endl;
int a, b;
std::cin >> a >> b;
std::cout << "The numbers between " << a << " and " << b << " are: " << std::endl;
for (; a < b && ++a < b; a)
{
std::cout << a << std::endl;
}
for (; b < a && ++b < a; b)
{
std::cout << b << std::endl;
}
}
It looks almost the same, but it works.
My questions is: I'm I missing something about the for loop, could I do it simpler?
PD: Just for loop, I'm not in the If chapter yet, I want to go step by step on the "C++ Primer 5th edition".
for is specified in terms of while, you aren't missing anything.
for (init-statement conditionopt;
iteration-expressionopt) statement
produces code equivalent to:
{ init-statement while (condition) { statement
iteration-expression; } }
Except that
Names declared by the init-statement (if init-statement is a declaration) and names declared by condition (if condition is a
declaration) are in the same scope (which is also the scope of
statement).
continue in the statement will execute iteration-expression
Empty condition is equivalent to while(true)
from cppreference
You don't need anything in iteration-expression for(;;) is equivalent to while(true)
it would be more normal to increment in the iteration-expression, and not repeat almost the same test.
#include <iostream>
int main()
{
std::cout << "Write two numbers: " << std::endl;
int a, b;
std::cin >> a >> b;
std::cout << "The numbers between " << a << " and " << b << " are: " << std::endl;
for (; a < b; ++a)
{
std::cout << a << std::endl;
}
for (; b < a; ++b)
{
std::cout << b << std::endl;
}
}
The for loop is intended to loop between two numbers. The use of your for loops unreadable for it's intentions. Take a look at this
int end = 10;
for (int begin = 0; begin < end; ++begin){/*do something*/}
This is the standard structure of a for loop. Now for your example you will get the following
#include <algorithm>
if (a > b) std::swap(a, b);
for (int begin = a; begin <= b; ++begin){
std::cout << begin << std::endl;
}
There is no need on using something like a < b && ++a < b since a < b is contained in ++a < b condition. So just using ++a < b you will get the same results.
Now about the for you should write it like this just to make your code a bit clear:
for (; a < b; ++a)
{
std::cout << a << std::endl;
}
I am not using the initialization sentence as you have already initialized your variables, however I encorage you to initialize a in the for sentence
In general terms, the for is divided in three sections:
for (<initialization sentence>; <condition sentence>; <post-execution sentence>)
The initialization only runs when the for sentence is reached, and the loop is running while the condition is met. The post-execution it is normally used to increase or change state of the variables involved in the condition criteria. The only constraint you have is that condition must be a boolean sentence.
None of those sections should be an assigment, a common comparison or a variable increment. You could use whatever fits your requirements and met the for constraints.
To sum up, a for sentence is a 'wrapped' structure of a while. You could get the same results with both. The difference is on a cleaner image of your code and a better understanding of the algorithms.
The code in the question is somewhat confusing, because it tries to do several things at once. I'd separate them.
Instead of writing two loops, I'd just change the limits:
if (v2 < v1)
std::swap(v2, v1);
Now it's easy:
while (++v1 < v2)
std::cout << v1 << '\n';
Same thing for the for loop. After adjusting the limits, just do it:
for ( ; ++a < b; )
std::cout << a << '\n';
Im having trouble with this recursion code. Basically I want the computer to "guess" in as little steps as possible the number that I am thinking of. However, everything works except the final output. The bounds are fine, and it narrows down the guess until it asks me if the number im thinking of is say 16, if I input "=" it should output 16 instead it always outputs 50. Could anyone help me locate the error?
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
unsigned int search (unsigned int boundInf, unsigned int boundSup);
int main ()
{
int b;
b = search (1, 100);
cout << "Your number must be : " << b << endl;
}
unsigned int search (unsigned int boundInf, unsigned int boundSup)
{
string magnitude;
int b;
b = (boundSup + boundInf) / 2;
cout << "Is your number <, > or = to " << b << "? ";
cin >> magnitude;
if (magnitude == "<") {
cout << "Between " << boundInf << " and " << b << endl;
search (boundInf, b);
}
else if (magnitude == ">") {
cout << "Between " << b << " and " << boundSup << endl;
search (b, boundSup);
}
return b;
}
You forgot to change the value of b when going deeper into the recursive function, this can be easily fixed by changing the search function like so:
unsigned int search(unsigned int boundInf, unsigned int boundSup)
{
string magnitude;
int b;
b = (boundSup + boundInf) / 2;
cout << "Is your number <, > or = to " << b << "? ";
cin >> magnitude;
if (magnitude == "<")
{
cout << "Between " << boundInf << " and " << b << endl;
b = search(boundInf, b);
}
else if (magnitude == ">")
{
cout << "Between " << b << " and " << boundSup << endl;
b = search(b, boundSup);
}
return b;
}
This code is for recursive function practice. When I run the code, it stops at the "POWER" cout line, then my compiler shows a segmentation error. The function that follows the POWER line is supposed to recursively raise number "a" to the power of number "b". I'm not sure how to fix this, can anyone help?
#include <iostream>
#include <string>
#include <vector>
using namespace std;
/**** Recursive backwards print, prints a string starting from last index to first*****/
void printReverse(string s, int i)
{
if(i < s.size())
{
printReverse(s.substr(1), i);
cout<<s[i];
}
else
{
return;
}
}
/**** Recursive power function, computes a^b, where b can be positive or negative*****/
int recPower(double a, int b)
{
int i = b; //i = b, so int a can be multiplied int b times
if (i == 0) //base
return 1;
else //multiply A by B, B times
{
a *= b;
return recPower(a, b); //recursive
i--; //decrement i until it equals 0
}
}
/**** Recursive string replace, replaces all instances of a character in a string with another character*****/
string recReplace(string s2, int i, char old, char neW)
{
if(s2[i] == old) //search for old char
{
i = neW; //replace it
i++; //iterate i
}
recReplace(s2, i, old, neW); //call function
return s2;
}
/**** Recursive list find > Searches if x exists in list, returns true if found, false otherwise*****/
int recListFind(vector<int> v, int i, int x)
{
if(v[i] == x)
{
cout << x << " exists in the vector."<<endl;
i++;
recListFind(v, i, x);
}
return true;
}
int main()
{
cout << "PRINT REVERSE" << endl;
cout << "----------" << endl;
string s1 = "hello world";
cout << "String: " << s1 << endl;
cout << "Reversed: ";
printReverse(s1, 0);
cout << endl;
/* Computes a^b (power function) */
cout << "POWER" << endl;
cout << "----------" << endl;
int a = 2, b = -3;
cout << a << "^" << b << " = ";
cout << recPower(a, b) << endl;
cout << endl;
/* Replaces a character in a string with a new one */
cout << "REPLACE" << endl;
cout << "----------" << endl;
string s2 = "-h-e-l-l-o-";
char oldChar = '-';
char newChar = ' ';
cout << "String: " << s2 << endl;
cout << "> Replace '" << oldChar << "' with '" << newChar << endl;
recReplace(s2, 0, oldChar, newChar);
cout << "String: " << s2 << endl;
cout << endl;
/* Searches for value in vector */
cout << "FIND" << endl;
cout << "----------" << endl;
int x = 7;
cout << "Does " << x << " exist in the vector? "; vector<int> v = {5, 1, 6, 7, 9};
cout << recListFind(v, 0, 7) << endl;
cout << endl;
return 0;
}
The issue is quite straight forward, you are doing the recPower function with b. In the function, if b is not 0, you call recPower with an unmodified value of b (whilst ever modifying a). This will always end up with infinite recursion which is going to overflow your stack.
A solution could be:
int recPower(double a, int b, int times) {
if (times == 0)
return a;
else
return b * recPower(a, b, --times);
}
int recPower(double a, int b) {
return recPower(a, b, b);
}
Even if you fix this, you have another problem. b can be negative, which based on your logic will continue to recurse while decrementing until it overflows and goes back to 0. You will cause this case with your first test case. You should think about the types that are allowed in this function, consider making them unsigned, or dealing explicitly with the negative b case.
I am lost, when I ran my program last night it ran fine. When I added the power() function, suddenly lines which ran fine without adding the new code now trigger an error message:
warning C4018: '<': signed/unsigned mismatch
Why?
I feel I don't have the chops to explain this, so please follow the code below.
PLEASE RUN THE CODE WITH AND WITHOUT THIS power() FUNCTION. When run with the power() function, it makes error C4018 on the for loops in the exam() function! When run without the power() function, it runs FINE!!
#include <string>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <cmath>
#include <numeric>
using namespace std;
///the offending function///
double power(double base, int exponent)
{
double product;
//double base; int exponent;
std::cout << "enter a value for base: " << endl;
std::cin >> base;
std::cout << "enter exponenent: " << endl;
std::cin >> exponent;
double result = 1;
for (int i = 0; i < exponent; i++)
{
result = result * base;
//product = base exponent;
}
std::cout << product;
return product;
}
///after here, things run fine if you X out the aforementioned function! Wow!
void exam()
{
std::vector<int> scores;
int F;
F = 0; //string names;
std::cout << "enter exam scores int:" << endl;
//std::vector <string> names;
while (F != -1)
{
std::cout << "Enter a new exame score:" << endl;
std::cin >> F;
scores.push_back(F);
}
if (F == -1)
{
std::cout << "end of score entering" << endl;
}
for (int i = 0; i < scores.size(); i++)
{
std::cout << scores[i];
}
/*
while (i < scores.size())
{
std::cout << scores[i];
i++;
}
*/
std::cout << "yay you made this work!!!!!!!!!!!!!" << endl;
}
int multiply()
{
int a;
int b;
a = 8;
b = 4;
std::cout << a * b << endl;
std::cout << "f*** yeah" << endl << endl;
return 0;
}
void test()
{
std::vector<int> newvector;
int T;
std::cout << "enter vector variables: " << endl;
std::cin >> T;
newvector.push_back(T);
while (T != -1)
{
std::cout << "enter new vector variables T " << endl;
std::cin >> T;
newvector.push_back(T);
if (T == -1)
{
newvector.pop_back();
}
}
std::cout << "end of NewVector data inputs:" << endl;
for (int W = 0; W < newvector.size(); W++)
{
std::cout << newvector[W] << endl;
}
}
int main()
{
power(2, 3);
exam();
/*int result = multiply();
std::cout << "endl ;" << endl;
test();
system("pause"); */
multiply();
string name;
int a;
std::cout << "enter a variable for your name: " << endl;
std::getline(cin, name);
if (name == "aaron")
{
std::cout << " what a dumb name, aAron?" << endl;
}
else if (name == "todd")
{
std::cout << "what a dottly name, Todd" << endl;
}
else
{
std::cout << "your name = " << name << endl;
}
//std::vector <string>
std::vector<int> asdf;
std::cout << "enter an int for a" << endl;
std::cin >> a;
asdf.push_back(a);
while (a != -1)
{
std::cout << "enter another A: " << endl;
std::cin >> a;
asdf.push_back(a);
if (a == -1)
{
asdf.pop_back();
}
} //set var; checks if d<size(); if so, JUMP to std::cout<<; when finished with body, find after size(); == "d++", then refer back to declaration)
/*/ for(int G = 0; G<asdf.size(); G++)
{
std::cout << asdf[G] << endl;
} */
for (int i = 0; i < asdf.size(); i++)
{
std::cout << asdf[i] << "f*** it works!!!!!! " << endl;
}
for (int d = 0; d < asdf.size(); d++)
{ //htt ps://youtu.be/_1AwR-un4Hk?t=155
std::cout << asdf[d] << ", ";
}
std::cout << endl;
std::cout << std::accumulate(asdf.begin(), asdf.end(), 0);
//std::cout<<
system("pause");
return 0;
}
The presence of the power function should have no effect on this problem. Possibly you aren't seeing the warnings because without the power function the program does not compile.
In
for (int W = 0; W < newvector.size(); W++)
newvector.size() returns an unsigned integer. int W is a signed integer. You're getting exactly what you asked for.
You can change int W to vector<int>::size_type W (but the less verbose size_t W should also work) to make the error message go away, but this is an error where you would likely have to add more than 2 billion items to the vector to see manifest.
Solution:
for (vector<int>::size_type W = 0; W < newvector.size(); W++)
However this is a good place for a range-based for loop
for (const auto &val: newvector)
{
std::cout << val << endl;
}
By letting the compiler figure out all the sizes and types your life is much easier.
This is repeated several times throughout the code.
Re: WHEN RUN, It makes error C4018 -
YOU made that error (warning, actually), not "it".
That warning is reported by compiler, so you haven't run anything yet...
Your newly added function uses uninitialized variable product; in my version of Visual Studio it is an error.
I'm (probably obviously) very new, and am attempting to build a calculator for my first project. I wanted to test my first concept, but upon compiling I get the 2059 error for the end brace of my InterFace struct as well as the first brace of my int AddUp. These seem like totally random errors. If it helps, the errors are for lines (10,1) and (16,2), although I suspect the 1 and 2 refer to number of like errors recorded? Any help would be appreciated.
1 #include <iostream>
2
3 struct InterFace
4 {
5 char Buttons[4][4]
6 {
7 Buttons[1] = "\u00B1";
8 std::cout << Buttons[1] << std::endl;
9 }
10 };
11
12
13 struct Addition
14 {
15 int AddUp[2]
16 {
17
18 }
19 };
int main()
{
std::cin.get();
}
You do not have the correct core concepts right, and should probably work through some C++ tutorials or courses before writing a program like this.
A few things:
The ± symbol is a unicode character. char in C++ refers to a single byte, usually an ASCII value if it's referring to text data. So it can't store the unicode +- symbol. Instead, you can store this unicode value in an std::string buttons[4][4]; (although the full answer is much more complicated).
In C++, 'a' refers to the character a, but "a" refers to a const char*. If it wasn't for the unicode issue, you should have used single quotes.
You try to assign to Buttons[1], but buttons is a 2-dimensional array. The element 1 also refers to the second element of the array, which may not be what you intended. Instead you could write Buttons[0][0]='a';
You don't have the concept of a member function/member variable down. The proper way to do this would be to have an initializer function and then call it.
Here is a fixed/working example, but I really recommend going through other tutorials first!
#include <iostream>
#include <string>
struct Interface {
std::string buttons[4][4];
void initialize_interface() {
buttons[0][0] = std::string("\u00B1");
std::cout << buttons[0][0] << std::endl;
}
};
int main() {
Interface my_interface;
my_interface.initialize_interface();
return 0;
}
As M.M. notes in the comments, a more paradigmatic approach would be the following:
#include
#include
struct Interface {
std::string buttons[4][4];
Interface() {
buttons[0][0] = std::string("\u00B1");
std::cout << buttons[0][0] << std::endl;
}
};
int main() {
Interface my_interface;
return 0;
}
Interface::Interface is called the constructor, and it runs upon initialization.
Since I wasn't able to build the calculator as I initially intended, I went a different route. I completed a basic one using switch instead.
#include <iostream>
int main()
{
int r;
int a;
int b;
int result1;
int result2;
int result3;
int result4;
int result5;
std::cout << "Please choose from the available options:" << std::endl << "0. Add" << std::endl << "1. Subtract" << std::endl << "2. Multiply" << std::endl << "3. Divide" << std::endl << "4. Modulo" << std::endl;
std::cin >> r;
switch (r % 5)
{
case 0:
std::cout << "You have chosen to Add, please enter two digits" << std::endl;
std::cin >> a;
std::cin >> b;
result1 = a + b;
std::cout << "Your sum is " << result1 << std::endl;
break;
case 1:
std::cout << "You have chosen to Subtract, please enter two digits" << std::endl;
std::cin >> a;
std::cin >> b;
result2 = a - b;
std::cout << "Your difference is " << result2 << std::endl;
break;
case 2:
std::cout << "You have chosen to Multiply, please enter two digits" << std::endl;
std::cin >> a;
std::cin >> b;
result3 = a * b;
std::cout << "Your product is " << result3 << std::endl;
break;
case 3:
std::cout << "You have chosen to Divide, please enter two digits" << std::endl;
std::cin >> a;
std::cin >> b;
result4 = a / b;
std::cout << "Your quotient is " << result4 << std::endl;
break;
case 4:
std::cout << "You have chosen to perform Modulus, please enter two digits" << std::endl;
std::cin >> a;
std::cin >> b;
result5 = a % b;
std::cout << "Your answer is " << result5 << std::endl;
break;
}
std::cin.get();
std::cin.get();
}