I am trying to learn C++ (Beginner). But I wonder how I can make an enumeration of variables in statements like if.
Do I just put a comma between variables?
What is the right syntax for this.. or is this all good?
#include <iostream>
using namespace std;
int main()
{
int a, b, c, d, e;
cin >> a >> b >> c >> d >> e;
if (a, b, c > e && a, b, c > d)
{
cout << a + b + c;
}
}
No, there is nothing in C++ like that. You'll need to split each of those into their own statement, like:
if (a > e && b > e && c > e && a > d && b > d && c > d){
However, the logic here can be simplified.
If you want a > e AND a > d, then you only need to show that a is greater than the larger of e and d. The reverse is true for a, b and c. In other words, you only need to check that the smallest of a/b/c is greater than the largest of e/d.
So this can become:
if (min({a, b, c}) > max(e, d)){
You can not do what you have tried there in the code.
The obvious way (beginner)way has been shown in the #scohe001's answer. However, when you learn at some point the templates and fold expressions, the following solution would be much compact and similar to what you have tried to do.
#include <iostream>
#include <utility>
template<typename... Args>
constexpr bool all_of_greater(const int lhs, Args&&... rhsArgs)
{
return ((lhs < std::forward<Args>(rhsArgs)) && ...);
}
Now you could do similar to what you have done in the code:
if (all_of_greater(e, a, b, c) && all_of_greater(d, a, b, c))
{
std::cout << a + b + c;
}
(See Online Demo)
Here's a reworked approach where the "values" and the "targets" are split into two separate vector structures to ease comparison:
#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
// Helper function to read an arbitrary number of entries into a vector
void read_n(std::vector<int>& list, const size_t n) {
for (size_t i = 0; i < n; ++i) {
int v;
std::cin >> v;
list.push_back(v);
}
}
int main() {
// Container to hold the values
std::vector<int> values;
read_n(values, 3);
// Container to hold the targets
std::vector<int> targets;
read_n(targets, 2);
// Ensure that for each target...
for (auto target : targets) {
// ...all of the values exceed that target...
if (!std::all_of(values.cbegin(), values.cend(), [target](int i) { return i > target; })) {
// ...or else it's a fail.
return -1;
}
}
// Use accumulate to compute the sum and display it.
std::cout << std::accumulate(values.cbegin(), values.cend(), 0) << std::endl;
return 0;
}
When writing code try and think in terms of structure and loops rather than just copy-pasting code to add more variables.
Related
I want to make a program that takes 4 numbers eg.(a, b, c and d) and checks if using arithmetic operators i can make the first 3 numbers result to the fourth number, like if the input is (3, 4, 5, 23) this will check out true because
3 + 4 * 5 = 23,So i want to make an array that has the operators and use a loop to check every possible combination, Hope i made it clear.
Edit:
Its actually codeforces problem, given 4 numbers. Check whether he could get the fourth number by using the arithmetic operators (+,−,×) between the other three numbers. Knowing that an operator can be used only once. in this format ->(a□b□c=d).My question was if there is a way to make it automatic or do i have to code every possibility manually So sorry for any confusion i may have caused.
You can't store the operators in an array, but you could make wrapper functions for them and store those in an array.
int add(int a, int b) {
return a + b;
}
int sub(int a, int b) {
return a - b;
}
int mul(int a, int b) {
return a * b;
}
int div(int a, int b) {
return a / b;
}
typedef int (*funptr)(int, int);
funptr arr[] = { add, sub, mul, div };
You can then call them like:
(arr[1])(2, 1) // call sub(2, 1)
The parentheses around arr[1] aren't needed in this case, but I like to put them for clarity.
No. You'd have to write a program to work this out. You could store something like function pointers to the arithmetic operators in an array, but I don't think that would help solve your problem. You'd still have to write the code to solve your problem.
Adding onto #CoffeeTableEspresso's answer, you can also put those function pointers into a map.
int add(int a, int b) {
return a + b;
}
int sub(int a, int b) {
return a - b;
}
int mul(int a, int b) {
return a * b;
}
int div(int a, int b) {
return a / b;
}
typedef int (*funptr)(int, int);
std::map<char,funptr> operators = {
{'+', add},
{'-', sub},
{'*', mul},
{'/', div}};
Then you can do
operators['+'](4,7);
Which might be a bit more readable, and you can iterate through these more easily.
I thought I would submit a compete answer. This works for positive numbers. It may take a bit more work to cover all the possibilities. And it does not answer to CoffeeTableEspresso's question about precedence. But it may help with your last question about if statements.
#include <iostream>
namespace {
auto add = [](int a, int b) {return a + b; };
auto sub = [](int a, int b) {return a - b; };
auto mult = [](int a, int b) {return a * b; };
auto divd = [](int a, int b) {return b ? a / b : -1; };
std::vector<int(*)(int, int)> ops = { add,sub,mult,divd };
}
int check(int* params)
{
for (size_t i = 0; i < 4; ++i)
for (size_t j = 0; j < 4; ++j)
{
auto result = ops[i](params[0], ops[j](params[1], params[2]));
if (params[3] == result)
return result;
else
std::cout << result << std::endl;
}
return -1;
}
int main()
{
int params[] = { 3, 4, 5, 23 };
std::cout << check(params);
}
Operators * / have a higher precedence than + -, so operator[i](A, operator[j](B, C)) solution doesn't really work.
You can write a little string calculator, and cycle through char-operators:
#include <iostream>
#include <sstream>
#include <vector>
#include <cmath>
double calculate(std::string str)
{
// calculator there
return -1;
};
int main()
{
std::vector<char> op = {'+', '-', '*', '/'};
std::vector<int> a = { 96, 3, 10, 42 };
for (auto op1: op)
for (auto op2: op)
{
std::stringstream ss;
ss << a[0] << op1 << a[1] << op2 << a[2];
double result = calculate( ss.str());
if (std::abs(a[3] - result) < 1E-6)
std::cout << ss.str() << " = " << a[3];
else
std::cout << ss.str() << " = " << result << " != " << a[3];
}
}
I need to count how many cubes of values between a and b (2 and 9 in this example) end with numbers between 2 and 5. Everything has to be done with recursion.
The output of this code is
part c = recc = 4
32767
0
It does not make sense to me. It calculates the value of n correctly, but then once asked to return it, returns either 0 or 32767, as if it was not defined.
Can anyone pinpoint the issue?
#include <iostream>
#include <string>
using namespace std;
void partb(int a, int b){
if(a<=b){
int p = (a*a*a)%10;
else if(p>=2 && p<=5){
cout<<a*a*a<<" ";
}
partb(a+1, b);
}
}
int recc(int n, int a, int b){
int p = (a*a*a)%10;
if(a>b){
cout<<"recc = " << n << endl;
return n;
}
else if(a<=b){
if(p>=2 && p<=5){
n++;
}
recc(n, a+1, b);
}
}
int partc(int a, int b){
int n = recc(0, a, b);
cout<<endl<< "part c = " << recc(0, a, b) << endl;
return n;
}
int main(){
int n=partc(2,9);
cout << n << endl;
return 0;
}
Not all control paths in your function return a value, so you were getting undefined behaviour when using the return value.
Now, this wasn't helped by the fact that the function itself is needlessly complicated. Let's rewrite it to use common practice for recursion:
int recc(int a, int b)
{
if (a > b) return 0;
int p = (a*a*a)%10;
int n = (p>=2 && p<=5) ? 1 : 0;
return n + recc(a+1, b);
}
Now your function is simpler. The recursion termination condition is right at the top. The function then decides whether a will contribute 1 or 0 to the count. And finally you return that value plus the count for a smaller range.
Notice how return n + recc(a+1, b); has broken the problem into a simple local solution combined with the recursive result of a reduced scope.
The invocation becomes simpler too, because you no longer have to pass in a redundant argument:
int partc(int a, int b)
{
int n = recc(a, b);
cout << endl << "part c = " << n << endl;
return n;
}
I've written a naive (only accepts integer exponents) power function for complex numbers (a home made class) using a simple for loop that multiplies the result for the original number n times:
C pow(C c, int e) {
C res = 1;
for (int i = 0; i==abs(e); ++i) res=res*c;
return e > 0 ? res : static_cast<C>(1/res);
}
When I try to execute this, e.g.
C c(1,2);
cout << pow(c,3) << endl;
I always get 1, because the for loop doesn't execute (I checked).
Here's the full code:
#include <cmath>
#include <stdexcept>
#include <iostream>
using namespace std;
struct C {
// a + bi in C forall a, b in R
double a;
double b;
C() = default;
C(double f, double i=0): a(f), b(i) {}
C operator+(C c) {return C(a+c.a,b+c.b);}
C operator-(C c) {return C(a-c.a,b-c.b);}
C operator*(C c) {return C(a*c.a-b*c.b,a*c.b+c.a*b);}
C operator/(C c) {return C((a*c.a+b*c.b)/(pow(c.a,2)+pow(c.b,2)),(b*c.a - a*c.b)/(pow(c.a,2)+pow(c.b,2)));}
operator double(){ if(b == 0)
return double(a);
else
throw invalid_argument(
"can't convert a complex number with an imaginary part to a double");}
};
C pow(C c, int e) {
C res = 1;
for (int i = 0; i==abs(e); ++i) {
res=res*c;
// check wether the loop executes
cout << res << endl;}
return e > 0 ? res : static_cast<C>(1/res);
}
ostream &operator<<(ostream &o, C c) { return c.b ? cout << c.a << " + " << c.b << "i " : cout << c.a;}
int main() {
C c(1,2), d(-1,3), a;
cout << c << "^3 = " << pow(c,3) << endl;}
What you wrote will read as follows:
for (int i = 0; i == abs(e); ++i)
initialize i with 0 and while i is equal to the absolute value of e (i.e. 3 at the beginning of the function call), do something
It should rather be
for (int i = 0; i < abs(e); ++i)
Tip: the code will throw at the first iteration due to the double conversion operator (and caused by a*c.b + c.a*b), but this is another issue: fix your complex (i.e. with imaginary part) printing function or implement a pretty printing method or such.
you should be using i != abs(e) or i < abs(e) as for loop condition. Currently you are using i == abs(e) which will fail in first try because:
i = 0
abs(e) = 3
so 0 == 3 is false and hence for loop will not execute.
I have two variables A and B and I want to write a code where if one of the two variables is equal to
151 or 156 or 720
and the other is not equal to one of these numbers then a third variable C = 0 is equal to one.
So for example
1) if A = 151 and B = 700 then C = 1
2) if A = 151 and B = 720 then C = 0
3) if A = 140 and B = 700 then C = 0
This is the code
int A = 0
cin >> A;
int B = 0
cin >> B;
int C=0;
int DECKlist[3] = {151,156,720}
for(int d=0; d<3;d++){
if(A== DECKlist[d]){
for(int w=0; w<3;w++){
if(B==DECKlist[w]) C=0;
else C=1;
}
}
if(B== DECKlist[d]){
for(int w=0; w<3;w++){
if(A==DECKlist[w]) C=0;
else C=1;
}
}
}
Is this OK? There are other better ways of doing it?
This is an exclusive OR, XOR. There is no logical XOR in C++, but you can use the bit-wise XOR for your case and exploit the fact that the result of a logical operator is a bool which will map to 0 or 1:
#include <iostream>
int main()
{
int A, B, C;
std::cin >> A;
std::cin >> B;
A = (A == 151 || A == 156 || A == 720);
B = (B == 151 || B == 156 || B == 720);
C = A ^ B;
std::cout << C << std::endl;
}
I've used a simple expression here to check whether a number is one of three supplied numbers. For larger sets of numbers to check against, you could use a, well, std::set.
You can use standard algorithms. For example you could use standard algoritnm std::binary_search along with bitwise XOR operator because array DECKlist is sorted
#include <algorithm>
#include <iterator>
//...
int DECKlist[] = { 151, 156, 720 };
//...
if ( std::binary_search( std::begin( DECKlist ), std::end( DECKlist ), A ) ^
std::binary_search( std::begin( DECKlist ), std::end( DECKlist ), B ) )
{
C = 1;
}
In this case you may add new values in the array and the approach will work as usual correctly. It does not depend on "magic numbers" and their quntity.:)
How about
int c=0;
for(int i=0; i<3; i++){
if(A == DECKlist[i]) c++;
if(B == DECKlist[i]) c++;
}
c = c%2;
Basically, count the number of matches, then make it zero if it was 2.
The first thing I'd do is hide the searching code. Here is a bit of C++ that will search an array (or any other container) linearly for if a given value is there. It uses a two C++11 features: std::begin and std::end, and auto typed variables:
#include <algorithm>
#include <utility>
#include <iterator>
template<class Array, class T>
bool find_in( Array const& arr, T const& t ) {
using std::begin; using std::end;
const auto b = begin(arr);
const auto e = end(arr);
const auto it = std::find( b, e, t ); // search the range for t
return !(e != it);
}
find_in is passed an array and a value, and returns true if that value is in the array.
We then use the same preamble. I avoid using namespace std; because it is a bad habit -- just name things with std:: or import individual symbols within a function scope.
#include <iostream>
int main() {
int A = 0
std::cin >> A;
int B = 0
std::cin >> B;
int C=0;
int DECKlist[3] = {151,156,720};
bool A_in_list = find_in(DECKlist, A);
bool B_in_list = find_in(DECKlist, B);
if (A_in_list != B_in_list)
C = 1;
std::cout << C << "\n";
}
The searching code, because I put it in a helper function, is really clean in the "core" logic of the program.
As we want to know when one is in the list, but not the other, we just compare the results using !=.
I want to find the lowest number of the four, but this looks kinda wierd , isnt there a smarter and shorter way to do it?
That is what I have:
int findlowest(int one, int two, int three, int four) {
int output = one //as of now , we will be outputting one , except if we find a lower score.
if(output > two) { out = two;} // if output is proven to be bigger than two, two is our new output.
if(output > three){ output = three;} //same operation with three
if(output > four){ output = four;} // same operation with four
return output;
}
std::min(a, std::min(b, std::min(c, d)));
Include <algorithm>.
c++11:
int minimum = std::min( { 1,2,3,4,5 } );
min_int = min(min(one, two), min(three, four));
int a[] = {1,2,3,4,5};
int minimum = *std::min_element(a, a+5);
Lots of answers saying to use the Standard library facilities - they're right, it covers this case! But, for the educational value, here's a slightly more concise way to do what you were doing:
int findlowest(int a, int b, int c, int d)
{
int of_a_b = a < b ? a : b;
int of_c_d = c < d ? c : d;
return of_a_b < of_c_d ? of_a_b : of_c_d;
}
Easily generalised for different types (though C++03 doesn't make it easy to generalise for arbitrary numbers of arguments):
template <typename T>
T findlowest(const T& a, const T& b, const T& c, const T& d)
{
const T& of_a_b = a < b ? a : b;
const T& of_c_d = c < d ? c : d;
return of_a_b < of_c_d ? of_a_b : of_c_d;
}