I'm having an issue with my C++ code that involves receiving input from the user and filling an array based on that input. For my function fillArray(), I need a way to read all inputs from one line and to fill an array with those inputs until the user inputs -1 at the end, something other than a positive integer, or exceeds the threshold of 20 elements.
For example, if I input
1 2 3 4 5 6 -1 on one line, I want the displayArray() function to output 1 2 3 4 5 6, or if i write 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21, I want displayArray() to output 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20.
It seems that whenever I input -1 at the end, displayArray() outputs something like
1 2 3 4 5 6 94837 or some arbitrarily big number. If somebody could help me out with this, I'd appreciate it, here's my code:
#include <iostream>
using namespace std;
const int CAPACITY = 20;
void displayArray(int array[], int numElements)
{
for (int i = 0; i < numElements; i++)
cout << array[i] << " ";
cout << endl;
}
void fillArray(int array[], int& numElements)
{
int arrayPosition = 0;
int testArrayPosition = 0;
int testArray[CAPACITY];
bool continueReading = true;
cout << "Enter a list of up to 20 integers or -1 to end the list";
do
{
cin >> valueEntered;
if (valueEntered == -1)
{
continueReading = false;
} else if (valueEntered != -1) {
array[arrayPosition] = valueEntered;
arrayPosition++;
}
} while ((continueReading==true) || (arrayPosition >= CAPACITY));
numElements = (arrayPosition+1);
}
int main()
{
int array[CAPACITY];
int numArrayElements = 0;
fillArray(array, numArrayElements);
displayArray(array, numArrayElements);
cout << "NumArrayElements: " << numArrayElements << endl;
}
The code you posted does not compile. You refer in several places to a variable valueEntered without ever having declared it.
Also, the following construct does not make sense:
if (valueEntered == -1)
{
[...]
}
else if (valueEntered != -1)
{
[...]
Since the condition expression of the second if statement is the exact negation of the condition expression of the first statement, the second if statement is superfluous and can be removed, like this:
if (valueEntered == -1)
{
[...]
}
else
{
[...]
However, since you stated in your question that anything else than a positive integer (not just -1) should cause your program to end, you will want to change that part of your program to the following:
if (valueEntered <= 0)
{
continueReading = false;
}
else
{
array[arrayPosition] = valueEntered;
arrayPosition++;
}
Also, as has already been stated by someone else in the comments section, the line
while ((continueReading==true) || (arrayPosition >= CAPACITY));
should be changed to
while ( continueReading && arrayPosition < CAPACITY )
and the line
numElements = (arrayPosition+1);
should be changed to
numElements = arrayPosition;
Related
this is my first time posting so I hope that I am doing this right. The instructions for this assignment are
Write a C++ program that implements the following algorithm:
input n
print n
if n = 1 then stop
if n is odd then n <-- 3n+1
else n <-- n/2
goto step 2
Example: given the input 22, the following sequence of numbers will be printed:
22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
do not use break to exit a loop
so far I have this code written out
#include <iostream>
using namespace std;
int main () {
int n = 0;
int set1 = 1;
int set22 = 22;
string outPut;
outPut = "22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1";
//input phase
cout << "Enter a number: ";
cin >> n;
//processing phase
if (n == 1)
{
}
else if (n != 22)
{
do
{
if (n % 2 != 0)
{
n = (3 * n) + 1;
}
else if (n % 2 == 0)
{
n = (n / 2);
}
cout << n << endl;
} while (n != set1 || n != set22);
}
//if statement for output
if (n == 22)
{
cout << outPut << endl;
}
}
but it seems that it is still not exiting the while loop once getting 1 or 22. Any ideas or help would be appreciated. Thanks
n != set1 || n != set22 will be always true because set1 and set22 have different values and n cannot be equal to both of them at once.
Use n != set1 && n != set22 instead of that.
This is what the code is for:
https://www.codechef.com/LRNDSA04/problems/STACKS
Here is the code snippet:
#include<bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int t; cin >> t;
while (t--)
{
int n; cin >> n;
vector<int> a;
while(n--) {
int x; cin >> x;
if(a.empty()) {
a.push_back(x);
} else {
vector<int>::iterator it = upper_bound(a.begin(), a.end(), x);
int pos = it - a.begin();
if(pos == a.size()) {
if(a[pos] > x) {
a[pos] = x;
} else {
a.push_back(x);
}
} else {
a[pos] = x;
}
}
}
cout << a.size();
for(auto e: a) {
cout << " " << e;
}
cout << "\n";
}
return 0;
}
Input to this program is:
2
6
3 4 5 1 1 2
8
14 5 13 19 17 10 18 12
The Unexpected output it generates:
3 1 1 2
3 5 10 12
If the input is changed to:
2
8
14 5 13 19 17 10 18 12
6
3 4 5 1 1 2
It shows up correct output:
4 5 10 12 18
3 1 1 2
The test case with 8 numbers as input if its position is altered in the input file. Then this behavior is observed.
When looking at the run of the code via gdb, it gives expected output for both input files, no problem then.
The output is not justified, what am I missing to see?
In this check:
if(pos == a.size()) {
if(a[pos] > x) { // this is UB
if the condition is true, then you are indexing into an invalid position of a, which invokes undefined behavior.
It seems you want to do
if(pos != a.size()) {
instead. The conventional way to check for this condition is
if(it != a.end()) {
I wrote a program to print a N x N square pattern with alternate 0's and 1's. For eg. A 5 x 5 square would looks like this:
I used the following code-
#include<iostream.h>
int main()
{
int i, n;
cin >> n; //number of rows (and columns) in the n x n matrix
for(i = 1; i <= n*n; i++)
{
cout << " " << i%2;
if(i%n == 0)
cout << "\n";
}
fflush(stdin);
getchar();
return 0;
}
This code works fine for odd numbers but for even numbers it prints the same thing in each new line and not alternate pattern.For 4 it prints this-
Where am I going wrong?
In my opinion the best way to iterate over matrix is using loop in another loop.
I think this code will be helpful for you:
for(i = 0; i < n; i++) {
for (j = 1; j <= n; j++) {
cout<<" "<< (j + i) % 2;
}
cout<<"\n";
}
where n is number of rows, i and j are ints.
Try to understand why and how it works.
If you're a beginner programmer, then I suggest (no offence) not trying to be too clever with your methodology; the main reason why your code is not working is (apart from various syntax errors) a logic error - as pointed out by blauerschluessel.
Just use two loops, one for rows and one for columns:
for (int row = 1; row <= n; row++)
{
for (int col = 0; col < n; col++)
cout << " " << ((row % 2) ^ (col % 2));
cout << "\n";
}
EDIT: since you wanted a one-loop solution, a good way to do so would be to set a flip flag which handles the difference between even and odd n:
bool flip = false;
int nsq = n * n;
for (int i = 1; i <= nsq; i++)
{
cout << " " << (flip ^ (i % 2));
if (i % n == 0) {
if (n % 2 == 0) flip = !flip;
cout << "\n";
}
}
The reason that it isn't working and creating is because of your logic. To fix this you need to change what the code does. The easiest way to handle that is to think of what it does and compare that to what you want it to do. This sounds like it is for an assignment so we could give you the answer but then you would get nothing from our help so I've writen this answer to guide you to the logic of solving it yourself.
Lets start with what it does.
Currently it is going to print 0 or 1 n*n times. You have a counter named i that will increment every time starting from 0 and going to (n*n)-1. If you were to print this number i you would get the following table for n=5
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
Now you currently check if the value i is odd or even i%2 and this makes the value 0 or 1. Giving you the following table
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
Now in the case of n=4 your counter i would print out to give you a table
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Now if you print out the odd or even pattern you get
1 0 1 0
1 0 1 0
1 0 1 0
1 0 1 0
This pattern diffrence is because of the changing pattern of printed numbers due to the shape of the square or more accurately matrix you are printing. To fix this you need to adjust the logic of how you determine which number to print because it will only work for matrixes that have odd widths.
You just need to add one more parameter to print the value. Below mentioned code has the updated for loop which you are using:
int num = 0;
for(i = 1; i <= n*n; i++)
{
num = !num;
std::cout << " " << num;
if(i%n == 0) {
std::cout << "\n";
num = n%2 ? num : !num;
}
}
The complete compiled code :
#include <iostream>
#include <stdio.h>
int main()
{
int i, n, num = 0;
std::cin >> n; //number of rows (and columns) in the n x n matrix
for(i = 1; i <= n*n; i++)
{
num = !num;
std::cout << " " << num;
if(i%n == 0) {
std::cout << "\n";
num = n%2 ? num : !num;
}
}
fflush(stdin);
getchar();
return 0;
}
So, I have a struct, consisting of 3 integers. This struct represents one "row" of my "table". Table is basically array of rows, called "v" Because of the task I have, I need to use this format instead of for example 2d array and these things. For now, I need to "lexicographically sort my rows" according to x,y and z. The problem is with the qsort function - it somehow messes up my whole array "v" that becomes useless. I don`t now what is the reason for it. The compare function compares the rows according to x, than according to y and than z (normal lexicographical sorting I think). Function printing just prints the table.
#include <iostream>
#include <stdlib.h>
using namespace std;
struct row {
int x, y, z;
};
int compar(const void* p1, const void* p2){
if(((row*)p1)->x < ((row*)p2)->x){
return -1;
}
if(((row*)p1)->x = ((row*)p2)->x){
if(((row*)p1)->y < ((row*)p2)->y){
return -1;
}
if(((row*)p1)->y = ((row*)p2)->y){
if(((row*)p1)->z < ((row*)p2)->z){
return -1;
}
if(((row*)p1)->z = ((row*)p2)->z){
return 0;
}
if(((row*)p1)->z > ((row*)p2)->z){
return 1;
}
}
if(((row*)p1)->y > ((row*)p2)->y){
return 1;
}
}
if(((row*)p1)->x > ((row*)p2)->x){
return 1;
}
}
void printing(row v[], int p){
cout << "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" << endl;
for (int i = 0; i < p; i++){
cout << v[i].x << " " << v[i].y<< ' ' << v[i].z << endl;
}
cout << "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" << endl;
}
int main(void){
int numOfRows;
cin >> numOfRows; //format of input needs this
row v[numOfRows];
for (int i = 0; i < numOfRows; i++) {
cin >> v[i].x >> v[i].y >> v[i].z;
}
qsort(v,numOfRows,sizeof(row),compar);
printing(v,numOfRows);
}
now I am posting inputs with outputs and you can clearly see, that some rows were duplicated in sorting process and some of them are missing completely.
3
1 2 3
1 4 5
1 2 4
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1 2 3
1 2 4
1 2 4
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
next input and output is:
4
100 100 100
100 100 100
100 99 99
99 99 100
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
99 99 99
99 99 99
99 99 99
99 99 100
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
How it should apparently look instead is for example:
3
1 2 3
1 4 5
1 2 4
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1 2 3
1 2 4
1 4 5
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
This would be the correct output of my qsort. Any help would be gladly appreciated, as I have absolutely no idea why this happens. I have been trying to solve this for the whole afternoon and I am out of ideas. Thanks a lot
A lot of your comparisons have = instead of ==, and that will lead to values being copied to places where they shouldn't be. If you set the warning level on your compiler high enough it should warn you about this.
The function compar does not have a return value at the end. It leads to undefined behavior.
You can simplify it to:
int compar(const void* p1, const void* p2)
{
row const* row1 = (row const*)p1;
row const* row2 = (row const*)p2;
if ( row1->x != row2->x )
{
return (row1->x - row2->x);
}
if ( row1->y != row2->y )
{
return (row1->y - row2->y);
}
return (row1->z - row2->z);
}
"Number pong" is what I am trying to do. Ex:
0 1 2 3 4 5 4 3 2 1 0 1 2 3 4 5 4 etc
I have tried several different things, incrementing one number, modal operators. I could not figure this out, and I could not figure out correct search words.
So:
int offset = 0;
int number = 0;
while(true) {
offset++;
number = offset%5; // idea 1
number = (offset%5)-5 // idea 2
number = (offset/5)%5 // idea 3
number = 5 - (offset%5) // idea 4
}
None of those work, obviously. I get patterns like 0 1 2 3 4 5 0 1 2 3 4 5 or just continuous numbers.
I would wrap this in an if(offset % 10 <= 5) { ... } else { ... } and use your existing ideas.
Regardless you're going to want to work % 10 since that's how long your cycle is.
Hint These sequences are very closely related:
0 1 2 3 4 5 4 3 2 1 0 1 2 3 4 5 4 ...
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 ...
#include <iostream>
int main()
{
int i = 0;
bool plus = true;
while(true) {
std::cout << i << std::endl;
if (plus) i++; else i--;
if (i == 5 || i == 0) plus = !plus;
}
}
Is there a requirement to generate the numbers in a single statement with variables and operators?
If not, then use an bool variable which switches its value (true means increasing, false means decreasing) from true to false and vice versa.
i.e.
int start = 0 ;
bool which_way = true ;
int loop_times = 100 ;
while(--loop_times) {
std::cout << start ;
start += which_way ? 1 : -1 ;
if(start % 5 == 0)
which_way = !which_way ;
}
Here is a crazy way of outputting the number pong (with set limit)
#include <stdio.h>
int main()
{
bool bFlip = false; //Decides if number will increase or decrease
int nLimit = 5; //How far up the number will count.
//Start at 0, keep going as long as number never reaches past the limit
//And increase/decrease depending on bFlip
for(int nNum = 0; nNum <= nLimit; (bFlip ? nNum++ : nNum--))
{
printf("%d ", nNum);
//When number reaches either end, do a barrel roll!
if (nNum % nLimit == 0)
{
bFlip = !bFlip;
}
}
return 0;
}
Be warned that this loop will go on forever so if you are going to go with this approach then you will need to set a limit on how many numbers you want to display.
Yet another crack at generating the sequence you're after:
#include <iostream>
#include <list>
#include <iterator>
int main() {
std::list<int> nums = {{0, 1, 2, 3, 4, 5}};
auto begin = nums.begin();
auto iterator = nums.begin();
auto end = nums.end();
auto loop_times = 100;
while (--loop_times) {
while (iterator != end) {
std::cout << *iterator++;
}
iterator--;
while (iterator != begin) {
std::cout<< *--iterator;
}
iterator++;
}
}
Thanks for the tips. I got it working with a single statement.
int count = 0;
int num = 0;
int out = 0;
while (count++ < 100) {
cout << abs( (num%10) - 5 ) << endl;
num++;
}
// Output: 5 4 3 2 1 0 1 2 3 4 5 4 etc
I'd probably do something like this:
// If you want in the range -val to val
//#define PONG(val, i) (abs(val%(i*4)-i*2) - i)
// If you want the range 0 to val
#define PONG(val, i) (abs(val%(i*2)-i))
int main() {
for(int i = 0; i < 100; i++) {
cout << PONG(i, 5) << endl;
}
}
Prints:
5 4 3 2 1 0 1 2 3 4 5 4 3 2 1 0 1 2 ...