So I'm working on this project where I have to gather 2 integers from a user 3 times (loop), and each time I have to print the two integers in ascending order. The restriction is that you can only have two cout statements within your loop (one is asking for their input and the second is outputting the ascending order).
My only issue with that is, when I think about ascending order, I would do it like (which has two count statements):
if (m<n) {
cout << m << n << endl;
if (m>n){
cout << n << m << endl;
So far, this is what I have:
#include <iostream>
using namespace std;
int main(int,char**) {
int n, m, z;
for (n=0;n<3;n++){
cout << "Give me two numbers: ";
cin >> m;
cin >> z;
//if (m>z);
//cout << m << z << "sorted is: " << m << z << endl;
// This is where I'm getting stuck because I need two count statements to organize in ascending order as shown above
}
}
So have you considered to change which variable holds the lower number? e.g.
if(m > n){
int temp = n;
n = m;
m = temp;
}
Then you can just use one print
cout << m << " " << n << endl;
This is where I'm getting stuck because I need two count[sic]
statements to organize in ascending order as shown above
You have marked this post as C++:
Additional options to consider:
use algorithm lib:
#include <algorithm>
std::cout << std::min(m,n) << " " << std::max(m,n) << std::endl;
or use conditional / ternary operator in your cout:
std::cout << ((m<n) ? m : n) << " " << ((n<m) ? m : n) << std::endl;
References are sometimes fun ... but perhaps this challenge is too trivial.
// guess m < n
int& first = m;
int& second = n;
if(!(m<n)) { first = n; second = m; }
std::cout << first << " " << second << std::endl;
Pointers can do the same:
// guess m < n
int& first = &m;
int& second = &n;
if(!(m<n)) { first = &n; second = &m; }
std::cout << *first << " " << *second << std::endl;
or you can use
lambda expressions, or
c++ functions, or
c++ class methods
But I think each of these would be directly comparable to either of the first alternatives.
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';
I am trying to split one large user given vector into x sub vectors. Everything "seems" to work as it should but the outcome is not right.
std::vector<std::vector<std::string>> split_to_sub_vectors(std::vector<std::string> initial_vector, int thread_amount) {
std::cout << "initial size: " << initial_vector.size() << std::endl;
int size_for_splitting = initial_vector.size();
std::cout << "split amount: " << thread_amount << std::endl;
int r = size_for_splitting / thread_amount;
std::cout << r << " need to be in each sub-vector" << std::endl;
std::cout << "There will be: " << size_for_splitting % thread_amount << " element remaining" << std::endl;
std::vector<std::vector<std::string>> perm_vector;
for (int x = 0; x < thread_amount; x++) {
std::vector<std::string> temp_vector;
for (int a = 0; a < r; a++) {
hm++;
std::cout << hm << std::endl;
temp_vector.push_back(initial_vector[hm]);
}
perm_vector.push_back(temp_vector);
}
std::cout << "Size of vector holding the sub vectors after splitting: " << perm_vector.size() << std::endl;
std::cout << perm_vector[0][0];
return perm_vector;
Running this code will give you this:
initial size: 7
split amount: 3
2 need to be in each sub-vector
There will be: 1 element remaining
1
2
3
4
5
6
Size of vector holding the sub vectors after splitting: 3
2
the vector i pass in is called test holds strings and is like so:
test.push_back("1");
test.push_back("2");
test.push_back("3");
test.push_back("4");
test.push_back("5");
test.push_back("6");
test.push_back("7");
Everything up until the last print statement seems to work. So perm_vector should hold 3 sub vectors containing every element in the main user given vector. When you print perm_vector[0][0] you would expect the output to be "1", but it is 2, also 7 should not be in the vector and 6 should be the last one but since it starts at 2, 7 is in it. the counter is defined outside of the function and it starts at 0. My question is why is it starting at 2?
I see two problems in your code:
hm is incremented before use. Furthermore, there is no point in making it global.
size_for_splitting is the result of an integer division, so the remainder is missing
I modified your code so the issues with hm are solved. I get the intended output <<1, 2>, <3, 4>, <5, 6>>, the 7 is missing as mentioned above.
#include <iostream>
#include<vector>
#include<string>
std::vector<std::vector<std::string> > split_to_sub_vectors(std::vector<std::string> initial_vector, int thread_amount) {
std::cout << "initial size: " << initial_vector.size() << std::endl;
int size_for_splitting = initial_vector.size();
std::cout << "split amount: " << thread_amount << std::endl;
int r = size_for_splitting / thread_amount;
std::cout << r << " need to be in each sub-vector" << std::endl;
std::cout << "There will be: " << size_for_splitting % thread_amount << " element remaining" << std::endl;
std::vector<std::vector<std::string> > perm_vector;
int hm = 0;
for (int x = 0; x < thread_amount; x++) {
std::vector<std::string> temp_vector;
for (int a = 0; a < r; a++) {
std::cout << hm << std::endl;
temp_vector.push_back(initial_vector[hm]);
hm++;
}
perm_vector.push_back(temp_vector);
}
std::cout << "Size of vector holding the sub vectors after splitting: " << perm_vector.size() << std::endl;
return perm_vector;
}
int main()
{
std::vector<std::string> test;
test.push_back("1");
test.push_back("2");
test.push_back("3");
test.push_back("4");
test.push_back("5");
test.push_back("6");
test.push_back("7");
std::vector<std::vector<std::string> > out = split_to_sub_vectors(test, 3);
}
Even if hm starts at 0, you increment it before you use it. Probably if you increment at the end of the internal for loop, you might get the output you expect. It's hard to tell the problem because I don't know what's in 'initial_vector', I assume initial_vector[0] = 1?
If you use the range-v3 library, implementing this logic becomes much easier, and less error prone:
#include <range/v3/all.hpp>
namespace rs = ranges;
namespace rv = ranges::views;
auto split_to_sub_vectors(std::vector<std::string> initial_vector, int thread_amount) {
auto res = initial_vector
| rv::chunk(thread_amount)
| rs::to<std::vector<std::vector<std::string>>>;
if (res.back().size() != thread_amount)
res.pop_back();
return res;
}
Here's a demo.
So I've made a basic polynomial class in C++ which stores the coefficients of these polynomials dynamically on the heap. I'm currently in the process of overloading operators so that I can add/subtract polynomials together in order to simplify them etc.
However I'm getting unexpected results when I try to overload the * operator. It looks like instead of returning the value of an index in the array it is returning the position of the array.
This is my *operator method in my .cpp file:
Polynomial Polynomial::operator*(Polynomial p) {
int maxDegree = (degree)+(p.degree - 1);
int *intArray3 = new int[maxDegree];
int i, j;
for (int i = 0; i < degree; i++) {
for (int j = 0; j < p.degree; j++) {
cout << getCoef(i) << " * " << p.getCoef(j) << " = " << getCoef(i)*p.getCoef(j) << endl;
intArray3[j] += (getCoef(i))*(p.getCoef(j));
cout << " intArray3[" << j << "] contains : " << intArray3[j] << endl;
}
}
return Polynomial(maxDegree, intArray3);}
The lines:
cout << getCoef(i) << " * " << p.getCoef(j) << " = " << getCoef(i)*p.getCoef(j) << endl;
and
cout << " intArray3[" << j << "] contains : " << intArray3[j] << endl;
return
10 * 1 = 10
intArray3[0] contains : -842150441
in my console. I'm assuming that the problem lies with my use of pointers somewhere but I can't for the life of me think why. I implemented this overload in a similar way to my + and - overloads and they work fine. Any assistance would be greatly appreciated. Cheers.
I've been given a following task: with the given double-linked list of real numbers you have to multiply the opposite elements of the list (first with the last, second with the last minus one, etc.) and add this product to the new list.
I.e.: we have that list:
1.1 2.2 3.3 4.4 5.5
Then we print
1.1 * 5.5 = 6.05;
2.2 * 4.4 = 9.68;
3.3 * 3.3 = 10.89;
And the final list is:
6.05 9.68 10.89
I've come up with the following naïve algorithm:
#include <iostream>
#include <list>
using namespace std;
int main() {
double x = 0;
double q = 0; //for the product of the elements
list <double> user_values, calculated_products;
//data entry
while ( cin >> x) {
user_values.push_back(x);
if (cin.get() == '\n') break;
}
//pairwise multiplication of the opposite elements (х1 * хn; x2 * xn-1; etc.):
for (auto p = user_values.begin(); p!=(user_values.end()); ++p){
cout << (*p) << " * " << (*user_values.rbegin()) << " = " ;
q = (*p) * (*user_values.rbegin()); //result of the multiplication
cout << q << "; " << endl;
calculated_products.push_back(q); //saving result to the new list
user_values.pop_back(); //removing the last element of the list, in order to iterate backwards. This is probably the most confusing part.
}
//result output:
cout << "we have such list of products: " << endl;
for (const auto& t: calculated_products){
cout << t << " ";
}
cout << endl;
return 0;
}
Since it is problematic to iterate through elements of the list backwards, I've only found the option of removing the last elements of the list.
So I wonder whether someone could came up with more elegant algorithm for doing that, or at least refine the one above.
You can use rbegin() to iterate from back to forth:
auto i1 = user_values.begin();
auto i2 = user_values.rbegin();
double bufResult = 0; //for the product of the elements
for(int i=0; i<user_values.size()/2; i++)
{
bufResult = (*i1) * (*i2); //result of the multiplication
cout << (*i1) << " * " << (*i2) << " = " << bufResult << "; " << endl;
calculated_products.push_back(bufResult); //saving result to the new list
i1++;
i2++;
}
Let me preface this by saying I'm still extremely new to C++ and want to keep things as simple as possible. I'm also pretty terrible at math.
Mostly, I'm looking to see if anyone can help my code so it will always give the correct result. I've mostly got it to do what I want, except in one scenario.
My code is trying to find out how many packages of hotdog weiners and how many packages of hotdog buns someone has purchased. Then it tells the user how many hotdogs they can make from that as well as how much leftover weiners or buns they would have. Assuming a package of weiners contains 12 and a package of buns contains 8, this is what I have come up with so far:
#include <iostream>
#include <cmath>
using namespace std;
void hotdog(int a, int b){ //a = weiner packages, b = bun packages
int weiners = 12 * a;
int buns = 8 * b;
int total = (weiners + buns) - (weiners - buns);
int leftOverWeiners = total % weiners;
int leftOverBuns = total % buns;
int totalHotDogs = total / 2;
cout << "You can make " << totalHotDogs << " hotdogs!" << endl;
if (leftOverWeiners > 0){
cout << "You have " << leftOverWeiners << " weiners left over though." << endl;
}else if (leftOverBuns > 0){
cout << "You have " << leftOverBuns << " buns left over though." << endl;
}
}
int main(){
int a;
int b;
cout << "Let's see how many hotdogs you can make!" << endl;
cout << "How many weiner packages did you purchase?: ";
cin >> a;
cout << "How many bun packages did you purchase?: ";
cin >> b;
hotdog(a, b);
return 0;
}
With this, I can always get the correct answer if the ratio of buns to weiners is the same or if there are more weiners than buns.
Because of the way I've set up total and/or leftOverBuns (lines 9, 11), I will never get the correct answer to how many left over buns there will be. I know there must be a simpler way to do this if not a way to modify my current code but I am stumped.
I know I left virtually zero notation, so if you would like some please let me know!
You're making it too complicated. Try this:
if(weiners > buns)
{
cout << "You can make " << buns << " hotdogs!" << endl;
cout << "with " << weiners-buns << " weiners left over" << endl;
return;
}
cout << "You can make " << weiners << " hotdogs!" << endl;
if(buns > weiners)
{
cout << "with " << buns-weiners << " buns left over" << endl;
}
The smaller of {buns, weiners} is the number of hot dogs, and the if-then blocks determine whether the function will report leftover buns or weiners.
#include <iostream>
void hotdog( int weinerspackages, int bunspackages ){
const int weinersPerPackage = 12;
const int bunsPerPackage = 8;
const int totalweiners = weinerspackages * weinersPerPackage;
const int totalbuns = bunspackages * bunsPerPackage;
int leftoverweiners = 0;
int leftoverbuns = 0;
int amountOfHotdogs = 0;
if( totalweiners > totalbuns ){
leftoverweiners = totalweiners - totalbuns;
amountOfHotdogs = totalbuns;
leftoverbuns = 0;
}
else if( totalbuns > totalweiners ){
leftoverbuns = totalbuns - totalweiners;
amountOfHotdogs = totalweiners;
leftoverweiners = 0;
}
else{
amountOfHotdogs = totalweiners;
leftoverweiners = 0;
leftoverbuns = 0;
}
std::cout << "You can make: " << amountOfHotdogs << " Hotdogs" << std::endl;
std::cout << "Leftover Weiners: " << leftoverweiners << " || Leftover Buns: " << leftoverbuns << std::endl;
}
int main(){
int PackagesW = 8;
int PackagesB = 12;
hotdog( PackagesW, PackagesB );
system("pause");
return 0;
}
Note: It is possible to do this with less variables, I declared this amount of variables to make it easier to understand what the numbers represent.
Assuming that it only takes one of each to make a hotdog, you can find which of the ingredients you have the least, and the amount of hotdogs you can make will be limited by the amount of that ingredient, that is why amountOfHotdogs takes the value of the lesser one. If both are equal in amount, then amountOfHotdogs can take the amount of either.
Only the ingredient with the larger amount will have leftovers, therefore leftoverweiners = totalweiners - totalbuns; when totalweiners > totalbuns and vice-versa.