using arrays to solve an equation - c++

so i wrote this code in c++ to solve this equation (x+y+z=30) where each of these variables has a limited amount of possible of values (1,3,5,7,9,11,13,15) so repetition is allowed and here's my code :
#include <iostream>
using namespace std;
int main()
{
int x[8]={1,3,5,7,9,11,13,15};
int y[8]={1,3,5,7,9,11,13,15};
int z[8]={1,3,5,7,9,11,13,15};
for (int i=0; i<8; i++)
{
for (int j=0; j<8; j++)
{
for (int k=0; k<8; j++)
{
if (x[i]+y[j]+z[k]==30)
{
cout << x[i] << "\n" << y[j] << "\n" << z[k]<< "\n"<< endl;
break;
}
}
}
}
}
now i don't know if this is the right way to approach it (I'm a beginner) but still this program did okay since it gave set of three number that did equal to 30 but it didn't stick to the possible values e.g (7,22,1), now that what you see their is the best i could come up with other attempts or fixes just made things worse e.g crashing or what so ever.
if you could help that would be great and most importantly tell me where i went wrong as this whole purpose of this is to learn not solve the problem.
thank you so much in advance !

You are using break statement which only breaks one of the loops. You have nested loops in your program, so i would recommend you to use goto: instead.
for (int i=0; i<8; i++)
{
for (int j=0; j<8; j++)
{
for (int k=0; k<8; j++)<----- it should be k++
{
if (x[i]+y[j]+z[k]==30)
{
goto stop;
}
}
}
}
stop:
cout << x[i] << "\n" << y[j] << "\n" << z[k]<< "\n"<< endl;
I actually ran the code and there is 2 more problems:
As mentioned on the answer below, it 3 odd numbers never add up to 30;
variables i , j and k need to be global variables. So initialize them before using in loops. Then it should work perfectly(if the number isn't even).

I don't see 22 in the values you initialized the arrays with. You also can just use one array with the possible values; 3 arrays are not needed.
I see that you only have odd integers as possible values. 3 odd integers can never sum up to an even integer like 30, so there is no solution to your problem as stated. The one solution you provided has 22 as one value, an even integer.

Related

C++ crashing when reading strings and storing on a vector

#include <iostream>
#include <vector>
using namespace std;
typedef vector<string> VS;
void back(VS &paraules, VS &sol, int n, int i) {
if(i == n) {
cout << "{" << sol[0];
for(int j = 1; j < n; j++) {
cout << "," << sol[i];
}
cout << "}" << endl;
}
else {
for(int j = 0; j < n; j++) {
sol[i] = paraules[j];
back(paraules, sol, n, i+1);
}
}
}
int main() {
int n;
cin >> n;
VS sol(n);
VS paraules(n);
for(int i = 0; i < n; i++) {
cin >> paraules[i];
}
cout << "This won t print";
back(paraules, sol, n, 0);
}
Pasted the whole code now. A backtracking that takes n words, and just prints all the permutations of the words.
I initially thought it was a problem with the reading since the this wont print wasn't printing. After some testing, I've discovered that commenting the function call on the last line makes the error disappear, and the code doesn't crash anymore.
So it's maybe the function? This still doesn't explain why it's not printing, since the call happens after the cout.
As an example input might be:
2 hi bye
It appears that you are going out of bounds in your back function for loop due to the if statement, try using n-1 instead
if(i == n-1)
The problem is that for the case when i == n is true, you've the statement:
cout << "," << sol[i]; //this leads to undefined behavior
In the above shown statement, the size of the vector sol is n. But note since i is equal to n in this case, you are going out of bounds by writing sol[i] and this will result in undefined behavior.
This is because, the indexing starts from 0 and not 1.
For example, say the vector sol size is 4. That is n = 4.
Now what you're essentially doing is :
cout << "," << sol[4];
But you can only safely use elements upto index 3, i.e., using sol[0], sol[1], sol[2], sol[3] is safe. On the other hand, using sol[4] leads to undefined behavior.
Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior.
For example here the program doesn't seem to crash but here it does crashes.
1For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program.
I don't believe there is an issue with the code itself. You are getting segment faults, but it would be from something else.
However, I am assuming your code looks like this:
#include <vector>
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
vector<string> v(n);
for(int i = 0; i < n; i++) {
cin >> v[i];
}
}
Because your code is missing a ending parenthesis, and a #include <iostream>. Would you mind copy and pasting your entire code, or linking a repository?

Unable to create a Two Dimensional Array with random parameters

So I am a Beginner in C and I was going through Arrays and i was having success with arrays restricted to bounds of constant integers...
But i also wanted to find out what happens if we give in a random number for the Numbers of Rows and columns..
However when i executed the program all was fine until the 4th element wherein Vscode with display an error message of Matrix.exe(The compiled file) not working..
I somehow guessed that the error was with vscode itself..(i might be horribly wrong)
So i went for an online compiler and didnt get the desired result..which was received easily with bounded constant integers..
The code is about treating a two dimensional array as a Matrix and then getting the desired result in a table form i.e to get a print of all the elements in a tabular form.
I will post the code now:
`
#include<iostream>
using namespace std;
int main()
{
int m,n;
int matrix[m][n];
cout<<"Please give the number of Rows:";
cin>>m;
cout<<"Please give the number of columns:";
cin>>n;
for (int i=0;i<m;++i)
{
for (int j=0;j<n;++j)
{
cout<<"Please enter matrix element:";
cin>>matrix[i][j];
}
}
//printingmatrix
cout<<"The Matrix is:";
for (int a=0;a<m;a++)
{
for (int b=0;b<n;b++)
{
cout<<matrix[a][b]<< " ";
}
cout<<endl;
}
}`
I dont actually know what the problem is the code might be incorrect but seemed logically correct to me...
I actually dont have any idea of why i am not receiving the result!
Also this is my first stack ques so sorry if I sucked at asking! ;)
Any help will be appreciated!
Thanks!
int m,n;
int matrix[m][n];
There are two big problems here.
Problem 1: You don't give any value to m nor n. Then you use these ungiven values as the size of an array. C++ is not a "dataflow" language. If you use a value, the program won't stop, and wait for you to initialise the value later. If you use an uninitialised value, then the behaviour of the program will be undefined. There are exceptions, but none that apply to this case, so the behaviour of your program is undefined. That is something to avoid. Solution: Don't ever use uninitialised values.
Problem 2: The values that you later give are not compile time constant. The size of an array variable must be compile time constant in C++. The program is ill-formed. Solution: If you need an array with runtime size, then you must allocate it dynamically. The simplest solution is to use std::vector provided by the standard library.
So I am a Beginner in C
Note that C and C++ are two distinct languages.
In addition to #eerorika's answer, if you want to have a modern solution to your problem you can use std::vector<std::vector<int>> to have a dynamic 2d array.
A std::vector can be resized by simply calling .resize(n).
A std::vector stores the length, get it by calling .size()
An element inside a vector can be accessed via []
With this information, you can rewrite your code to look like this:
#include <iostream>
#include <vector>
int main() {
int m, n;
std::cout << "Please give the number of Rows: ";
std::cin >> m;
std::cout << "Please give the number of columns: ";
std::cin >> n;
std::vector<std::vector<int>> matrix;
matrix.resize(m);
for (int i = 0; i < matrix.size(); ++i) {
matrix[i].resize(n);
}
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
std::cout << "Please enter matrix element [" << i << ", " << j << "] : ";
std::cin >> matrix[i][j];
}
}
std::cout << "The Matrix is:\n";
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
std::cout << matrix[i][j] << " \t";
}
std::cout << '\n';
}
}
Example run:
Please give the number of Rows: 3
Please give the number of columns: 2
Please enter matrix element [0, 0] : 0
Please enter matrix element [0, 1] : 5
Please enter matrix element [1, 0] : -3
Please enter matrix element [1, 1] : 11
Please enter matrix element [2, 0] : 20
Please enter matrix element [2, 1] : 99
The Matrix is:
0 5
-3 11
20 99
You can read here why using namespace std; is considered bad practice.
Read about range-based for loop to learn more on how to use std::vector in a modern approach.
The problem with your original code is that C++ does not allow you to declare or initialize arrays with non-constant values for dimensions.
You can easily fix this issue if you use C++ STL vector as shown in the code below:
First, please note that you will need to include the header vector
Second, please see how I instantiate the vector matrix as a 2D array in the code. And, I also removed one line of your old code, and instead added the declaration for the vector matrix.
#include<iostream>
#include<vector> // This line must be added to use STL vector
using namespace std;
int main()
{
int m,n;
//int matrix[m][n]; // I removed this line
cout<<"Please give the number of Rows:";
cin>>m;
cout<<"Please give the number of columns:";
cin>>n;
vector<vector<int>> matrix(m, vector<int>(n, 0) ); // I added this line
for (int i=0;i<m;++i)
{
for (int j=0;j<n;++j)
{
cout<<"Please enter matrix element:";
cin>>matrix[i][j];
}
}
//printingmatrix
cout<<"The Matrix is:";
for (int a=0;a<m;a++)
{
for (int b=0;b<n; b++)
{
cout<<matrix[a][b]<< " ";
}
cout<<endl;
}
}
Note: I have tested and verified the code above run well. Please let me know if you have any issue.

Trying to create a better loop for naming array elements

I have started studying arrays and have just started making some practice but I am having some problems with using loops to name the elements inside of a specific array.
I was trying to make this piece of code that assigned the numbers from 1 up to 12(to resemble the months of the year) to the ints inside of the array, this is what I came up with:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int array[12];
for (int i = 0; i < 12;) {
cout << "Month number " << i + 1 << endl;
array[i] = (i++);
}
return 0;
}
What I don't like about this is the fact that I had to leave the increment/decrement space inside of the for loop empty. I had initially tried making the code look something like this:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int array[12];
for (int i = 0; i < 12; i++) {
cout << "Month number " << i + 1 << endl;
array[i] = i++;
}
return 0;
}
But this way, even if the first element of the array came out correct, the subsequent ones didn't. I think the reason for this is that the i++ in the last statement of the loop makes the value of i increment but I couldn't find a way around it without having to add another line with i-- or doing as I did in the first code I posted.
Could anyone offer me a hand in understanding how to make it so that i can store the value of i, incremented by one, inside of that specific array element, without incrementing it for the whole loop(if it is possible)?
I know there are ways around it, just like I showed in the first code i posted, but it's something that's bugging me and so I would like to make it more visually pleasing.
Please, keep in mind that I am just a beginner :)
Thanks in advance for the answers, and sorry for the long question.
Edit: Apparently, coding like this:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int array[12];
for (int i = 0; i < 12; i++) {
cout << "Month number " << i + 1 << endl;
array[i] = i + 1;
}
cout << array[4] << endl;
return 0;
}
makes it so that the program works correctly and looks like I wanted, but I can't comprehend why it does :(
Edit 2: Apparently, as UnholySheep pointed out, I missed on the fact that + 1 does not modify the value of the integer, while ++ does.
Thanks to everyone that answered and explained how ++ and +1 work!
Simply do i+1 again.
for (int i = 0; i < 12; i++)
{
cout << "Month number " << i + 1 << endl;
array[i] = i + 1;
}
Now it's obvious you actually want to start at 1 and go to 12, so this seems somewhat better with less repetition:
for (int i = 1; i <= 12; i++)
{
cout << "Month number " << i << endl;
array[i-1] = i;
}
EDIT: As for your edit, the reason why this works is because i++ operator works on the particular i variable. It increments that existing i by one, making it so that the next time you access i, it will be 1 more than it was before.
Writing i+1, on the other hand, creates a completely new, temporary, variable (actually a constant). So when you write
array[i] = i+1;
you're saying that you want i to remain unchanged, but you want to create a new number, one bigger than i, and put that new number into the array.
You can even write it out longer to be completely explicit:
int newNumber = i+1;
array[i] = newNumber;
for (int i = 0; i < 12; i++) {
cout << "Month number " << i + 1 << endl;
array[i] = i+1;
}
No reason to increment i in the loop

C++: Displaying characters

I'm learning and improving my programming skills from "Think Like a programmer" book and I was asked to display this kind of pyramid.
########
######
####
##
I did it with this code
for(int i = 0; i < 4; i++){
for(int k = 0; k < i; k++)
cout << ' ';
for(int j = 0; j < 8 - i * 2; j++)
cout << '#';
cout << '\n';
}
But... the questions was "Using the same rule as the shapes programs from earlier in the chapter (only
two output statements—one that outputs the hash mark and one that outputs
an end-of-line), write a program that produces the following shape:"
I'm not sure, but is it possible to display something like this with only 2 statements and without using space character?
edit.
Thanks for an answer guys. But according to author I should do this with only cout << '#' and cout << '\n'. And here is my point, because it seems that manipulating with some methods or functions is not an option.
Write a program that uses only two output statements, cout << "#" and cout << "\n",
to produce a pattern of hash symbols shaped like a ...
Of Course with use of loops :P
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
for(int i = 0; i < 4; i++) {
cout << setw(8-i) << string(8-i*2, '#') << endl;
}
return 0;
}
Unfortunately, the answer to this question is much simpler: author error. Those first few questions should have been worded to allow the use of a single space output as well (cout << " ";). I don't know how we all missed this in editing, and I apologize for the confusion this has caused. In general, any exercise that is intended to force the reader to go "digging" will be clear on that point.
By the way, this and other issues from the first edition are discussed in the document that can be found on my site here. If you have further questions or problems with the book, please do contact me.
You can check the position in a loop for every line. This combined with a 3 operand operator could solve this with two output statement.
for(int i = 0; i < 4; i++){
for(int k = 0; k <= 8-i; k++)
cout << k<i ? ' ' : '#';
cout << endl;
}
Leading space characters will be there anyway, You can not make an "empty" space instead of them.
I don't know if it's about the "art" of not using cout << ' ', but in that case there is another neat solution:
#include <iostream>
int main() {
for (int i = 0; i < 4; ++i, std::cout << '\n') {
for (int j = 0; j < 8-i; ++j) {
std::cout << (char)('#' - 3*(j<i));
}
}
}
And, another, even more obscure version that uses the ASCII representation rather than writing ' ' explicitly, using only one for-loop:
int main() {
for (int i = 1; i < 37; ++i) {
std::cout << (char)(35-3*((i%9)<=((i-1)/9)) - 3*((i%9)>=(9-(i-1)/9)) \
- 22*(!(i%9)) );
}
}
I do not say this is good programming practice, but maybe it helps someone in realizing - again - that it's in the end all numbers and registers.

Using ASCII characters in C++ program

I've been trying to print out _ <------ this character in a 2D array... But when I
tried compiling the code, it returned some garbage numbers. I think I'm doing something wrong... can anyone please help me out to solve this problem ?
void main (){
int A[9][9];
for (int i=0; i<9; i++){
for (int j=0; j<i; j++){
A[i][j]= '_';//I am doing this part wrong.
}
}
for (int r=0; r<9; r++) {
for (int c=0; c<9; c++)
cout << setw(3) << A[r][c];
cout << endl;
}
system("pause");
}
A is an int array. So cout would try to print an integer. Try cout << char(A[r][c]);
The std::cout::operator<< operator is overloaded for several data types in order to facilitate (automagically-)formatted output. If you feed it an int, then it will print a number. If you give it a char, it will try to print it as a character. So either declare your array as an array of char, or cast the array member when printing:
cout << static_cast<char>(array[i][j]) << endl;
1. Assign the ASCII value to integer array rather than '_'. It will work even without change; but i feel it looks cleaner.
A[i][j]= 95; // try this instead of '_'
While printing, cout can print any data type without casting, but since we are looking for character to be printed, try explicit conversion.
cout << setw(3) << char(A[r][c]);
Not sure about the compiler you are using, but its a better practice to initialize the array to avoid garbage value tampering with your output