New integer array shifted to the right? - c++

I should input the array x[ ] and create the new array y[ ], that is shifted to the right from the original.
I'm havong trouble with the first element, y[0]
for ex. if i input {7, 8, 4, 2, 3}
the code below returns: {-693726240, 7, 8, 4, 2}
where is the error?
Thanks in advance.
#include <iostream>
using namespace std;
int main()
{
int i, j, n, m=0, x[100],y[100];
cin >>n;
for(int i=0; i<n; i++)
{
cout << "enter "<< i+1 <<". element: ";
cin >> x[i];
if (i>0)
y[m++] = x[i-1];
else //THIS IS FOR Y[0] BUT DOESN'T WORK
y[m++] = x[n-1];
}
// ARRAY SHIFTED TO THE RIGHT:
for(int j=0; j<m; j++)
{
cout << y[j]<<" ";
}
return 0;
}

Loop starts with i == 0. You read the i-th element at i-th iteration. i == n - 1 is yet some time in the future when you read x[n - 1] in the 0-th iteration. C++ is not obliged to initialise variables for you to any particular value, so when you read from a not-yet-initialised location, you are likely to get garbage (in this case, -693726240).
To solve this, you have to solve the time paradox. Don't assign anything at iteration 0; wait till the loop is done and all data is in, and only then sneak back and fill in the 0-th element.
Alternately, read the entirety of x first, then when you know all the values, use your current algorithm to shift x into y (i.e. separate the current do-everything loop into a read loop and shift loop). This way, all the x values will be known when you start on y, and you won't have any time-travel mishaps.

I am assuming that you are looking for a circular shift given that you wrote y[m++] = x[n-1]
Amadan's answer highlights a way of solving your problem, here is some code you can follow :
for(int i = 0;i < n-1;i++){
cin>>x[i];`
y[i+1] = x[i];
}
cin>>x[n-1];
y[0] = x[n-1];

got it, great, #Amadan thanks for explanation and quick answer
I also removed "j" and "m" as separate variables for the new array,
think it's not needed actually, I can use the same "i" and "n" that are used for the original array (right? Or should I keep the new variables?)
Here's corrected code that works:
#include <iostream>
using namespace std;
int main()
{
int i, j, n, m=0, x[100],y[100];
cin >>n;
for(int i=0; i<n; i++)
{
cout << "enter "<< i+1 <<". element: ";
cin >> x[i];
if (i>0)
y[i] = x[i-1];
}
y[0] = x[n-1];
// ARRAY SHIFTED TO THE RIGHT:
for(int i=0; i<n; i++)
{
cout << y[i]<<" ";
}
return 0;
}

also I tried the other alternative #Amadan suggested, and used it also for left shifting
- first input all the elements, then assigning another array elements when they're all known
I consider this as the best one, tested and working. Thanks again:
#include <iostream>
using namespace std;
int main()
{
int i, n, x[100],y[100], z[100];
cin >>n;
for(int i=0; i<n; i++)
cin >> x[i];
// ARRAY SHIFTED TO THE RIGHT:
for(int i=0; i<n; i++)
{
if (i > 0) y[i] = x[i-1];
else y[i] = x[n-1];
cout << y[i]<<" ";
}
cout << endl;
// ARRAY SHIFTED TO THE LEFT:
for(int i=0; i<n; i++)
{
if (i < n-1) z[i] = x[i+1];
else z[i] = x[0];
cout << z[i]<<" ";
}
return 0;
}

Related

i am only getting the output right if i say i is int specially in for loop

#include <iostream>
using namespace std;
// finding the required sum of subarray
int main()
{
int n,s;
int i=0,j=0,st=-1,en=-1,sum=0;
cin>>s; //input required sum
cin>>n;
int a[n];
for(int i=0;i<n;i++){ // here if i only mention int again i //am getting the output or else the values of st and en are printing //out the same as i initialize
cin>>a[i];
}
while (j<n){
sum+=a[j];
while(sum>s){
sum-=a[i];
i++;
}
if(sum==s){
st=i+1;
en=j+1;
break;
}
j++;
}
cout<<st<<" "<<en<<" ";
return 0;
the output is -1 -1
and if i mention "int i" again in for loop of inputing array i a getting the answer.
i want to know the reason i already intialize i before why do i need to do it again
The problem statement is unclear, I'm assuming you simply want the indexes of the repeating numbers in array a. You are correct for the most part, using b[i] = i is the problem. If you understand what a vector is, then simply create a vector like this and push the indexes in the vector. For example,
vector<int> b;
and inside the a[i] == a[j] condition,
b.push_back(i);
then finally print out result like,
for(int i = 0 ; i < b.size() , i++)
cout << b[i] << " ";
If you're unfamiliar with vectors, simply use another variable cnt to update index of array b
int a[n], i, b[n], j, cnt = 0;
and inside the a[i] == a[j] condition,
b[cnt] = i;
cnt++;
and finally
for(int i = 0 ; i < cnt ; i++)
cout << b[i] << ' ';

The solution is executed with error 'out of bounds' on the line 7

I have received this bound error though the sample input and output match. I tried several ways to solve this error, but I couldn't. Please help me to overcome this problem. And also please, explain why? what is the main reason for this error?. My code as follows:
#include <iostream>
using namespace std;
int main(){
int a[4];
for(int i=1; i<=4; i++){
cin >> a[i];
}
string s;
cin >> s;
int sum = 0;
for(int i =0; i<s.size(); i++){
if(s[i]=='1'){
sum=sum+a[1];
}
else if(s[i]=='2'){
sum+=a[2];
}
else if(s[i]=='3'){
sum+=a[3];
}
else if(s[i]=='4'){
sum+=a[4];
}
}
cout << sum << endl;
}
Sample input:
1 2 3 4
123214
Output:
13
Array indexes start at 0 so a[4] is out of bounds in your case.\
Since we're here I recommend to not use C arrays. Use std::array or std::vector instead.
Also it's better to use the range for.
First of all, this is not correct
int a[4];
for(int i=1; i<=4; i++){
cin >> a[i];
}
arrays in C++ are indexed from 0, so it should be if you want to have a[1] = 1
int a[5];
for(int i = 0; i < 5; i++){
cin >> a[i];
}
Side note. You dont need the "look-up array". To sum numbers, you can just do:
sum += (s[i] - '0');
int a[4];
for(int i=1; i<=4; i++){
The variable declaration for a allocates indices 0 to 3 (4 elements total), yet you're trying to access 0 to 4 via i

Error:No matching function for call to

I am very very new to C++ and I am trying to call the function "jacobi" which performs a user specified number of iterations for the jacobi method (or at least I hope so). On the line where I call 'jacobi' I get the error "No matching function to call to "jacobi". I have read other posts similar to this one and have tried to apply it to my own code but I have been unsuccessful. Maybe there are other issues in my code causing this problem. As mentioned I am very new C++ so any help would be appreciated and please break it down for me.
#include <iostream>
using namespace std;
void jacobi (int size, int max, int B[size], int A[size][size], int init[size], int x[size]){
////
//// JACOBI
////
int i,j,k,sum[size];
k = 1;
while (k <= max) // Only continue to max number of iterations
{
for (i = 0; i < size; i++)
{
sum[i] = B[i];
for (j = 0; j < size; j++)
{
if (i != j)
{
sum[i] = sum[i] - A[i][j] * init[j]; // summation
}
}
}
for (i = 0; i < size; i++) ////HERE LIES THE DIFFERENCE BETWEEN Guass-Seidel and Jacobi
{
x[i] = sum[i]/A[i][i]; // divide summation by a[i][i]
init[i] = x[i]; //use new_x(k+1) as init_x(k) for next iteration
}
k++;
}
cout << "Jacobi Approximation to "<<k-1<<" iterations is: \n";
for(i=0;i<size;i++)
{
cout <<x[i]<< "\n"; // print found approximation.
}
cout << "\n";
return;
}
int main (){
// User INPUT
// n: number of equations and unknowns
int n;
cout << "Enter the number of equations: \n";
cin >> n;
// Nmax: max number of iterations
int Nmax;
cout << "Enter max number of interations: \n";
cin >> Nmax;
// int tol;
// cout << "Enter the tolerance level: " ;
// cin >> tol;
// b[n] and a[n][n]: array of coefficients of 'A' and array of int 'b'
int b[n];
int i,j;
cout << "Enter 'b' of Ax = b, separated by a space: \n";
for (i = 0; i < n; i++)
{
cin >> b[i];
}
// user enters coefficients and builds matrix
int a[n][n];
int init_x[n],new_x[n];
cout << "Enter matrix coefficients or 'A' of Ax = b, by row and separate by a space: \n";
for (i = 0; i < n; i++)
{
init_x[i] = 0;
new_x[i] = 0;
for (j = 0; j < n; j++)
{
cin >> a[i][j];
}
}
jacobi (n, Nmax, b, a, init_x, new_x);
}
The problem:
There are several problems, related to the use of arrays:
You can't pass arrays as parameter by value.
You can't pass multidimensional arrays as parameter if the dimensions are variable
You can't define arrays of variable length in C++
Of course there are ways to do all these kind of things, but it uses different principles (dynamic allocation, use of pointers) and requires additional work (especially for the access of multidimensional array elements).
Fortunately, there is a much easier solution also !
The solution:
For this kind of code you should go for vector : these manage variable length and can be passed by value.
For the jacobi() function, all you have to do is to change its definition:
void jacobi(int size, int max, vector<int> B, vector<vector<int>> A, vector<int> init, vector<int> x) {
int i, j, k;
vector<int> sum(size); // vector of 'size' empty elements
// The rest of the function will work unchanged
...
}
Attention however: the vectors can be of variable size and this jacobio implementation assumes that all the vectors are of the expected size. In professional level code you should check that it's the case.
For the implementation of main(), the code is almost unchanged. All you have to do is to replace array definitions by vector definitions:
...
vector<int> b(n); // creates a vector that is initialized with n elements.
...
vector<vector<int>> a(n,vector<int>(n)); // same idea for 2 dimensional vector (i.e. a vector of vectors)
vector<int> init_x(n), new_x(n); // same principle as for b
...

Weird Array Stuff (Array indexes getting values without me setting it)

I am trying to write a sudoku solver.
I got the input almost done, but something strange started happening. On the index [i][9] of int sudoku[i][9], there are numbers present that I have never put there.
For example, when I run the code below with the input that is commented below using namespace std;, the output is:
410270805
085146097
070580040
927451386
538697412
164328759
852704900
090802574
740965028
Of course, I only need 0 through 8, but I was wondering what is causing integers to appear at the 9th index.
This is the code:
#include <iostream>
#include <math.h>
#include <cstdlib>
using namespace std;
/*
410270805
085146097
070580040
927451386
538697412
164328759
852704900
090802574
740965028
*/
int main()
{
int sudoku[9][9];
int solving[9][9][9];
int input;
for (int i=0; i<=8; i++) {
cin >> input;
int j;
int k;
for (j=8, k=1; j>=0; j--, k++) {
int asdf = input/pow(10,k-1);
sudoku[i][j] = asdf % 10;
}
}
cout << endl;
for (int i=0; i<=8; i++) {
for (int j=0; j<=9; j++) {
cout << sudoku[i][j];
}
cout << endl;
}
return 0;
}
Accessing elements outside of the defined region of an array is Undefined Behavior (UB).
That means it could:
Allow you to access uninitialized space (what yours is doing hence the random numbers)
Segfault
Any number of other random things.
Basically don't do it.
In fact stop yourself from being able to do it. Replace those arrays with std::vectors and use the .at() call.
for example:
std::vector<std::vector<int>> sudoku(9, std::vector<int>(9, 0));
for (int i=0; i<=8; i++) {
for (int j=0; j<=9; j++) {
cout << sudoku.at(i).at(j);
}
cout << endl;
}
Then you will get a thrown runtime exception that explains your problem instead of random integers or segfaults.
I think I found your problem, at your very last for loop you used j <= 9 instead of j <= 8. You then tried to write (j) leaving the possibility of it writing 9 wide open. Try replacing that 9 with 8.

Arrays homework question

I have this homework question:
Write and test a program that read in n integers (max value for n is 20), each integer has
a value between 0 and 100 inclusive. You program should then print out the unique values
among the input numbers and the count of these values.
Sample input:
Enter a the number of integers = 8
Enter 8 integers: 5 6 7 6 6 17 17 35
Sample output:
Number 5: 1
Number 6: 3
Number 7: 1
Number 17: 2
Number 35: 1
This is what I did:
#include<iostream>
using namespace std;
int main(){
int a[20], n;
cout<< "Please enter the number of integers= ";
cin>> n;
cout<<"Please enter"<< n<<" integers: ";
for (int i=0; i<n; i++)
cin >> a[i];
for (int k=0; k< n; k++){
int sum=0;
for (int i=0; i< n; i++){
if (a[i]==a[k])
sum= sum+1;
}
cout<< "Number "<< a[k]<<" : "<< sum<< endl;
}
}
Consider that when you iterate through your list, you're checking all values with both i and k. So essentially, if you had a list of 1 1 2 2, then the first one will count itself, and the 1 at a[1]. The second 1 will count the first 1 and itself, giving you your repeated output.
A way to simplify this would be to make use of a hash_map, or some similar structure (I'm not as familiar with C++) that maps a key to a value and doesn't allow repeats. This would allow you to record the unique numbers as keys, and increment them with only one pass through the list. The advantage to using the hashMap is that you make your program linear (although I don't think that's really a concern at this stage).
The simplest way to solve your problem, however would be to use a Bin sort technique. The underlying idea here is that your number range is simply 0 to 100, meaning you could create bins for 0 to 100 and increment each one. Again, this is Java code, and doesn't have any actual input for a.
// Count is the key, it uses indexes from 0 to 100, with null values of
// 0 after initialized. Simply iterate the loop, and use the value of
// a[k] to increment the corresponding count in the count array.
// Finally, print the results
int[] a = new int[20];
int[] count = new int [101];
for (int k = 0; k < a.length; k++){
count[a[k]]++;
for (int i = 0; i < count.length; i++){
if (count[i] > 0)
System.out.println(i + ": " + count[i]);
}
Add another bool b[20] ,initialize it with true. Then every time you detect a[k] is a dupe, you set b[k] = false. Only print a[k] if b[k] == true
for (int k = 0; k < n; k++) {
if (!b[k]) {
continue;
}
int sum = 0;
for (int i = 0; i < n; i++) {
if (a[i] == a[k]) {
sum = sum + 1;
b[i] = false;
}
}
cout << "Number " << a[k] << " : " << sum << endl;
}
You have to keep a running count of the items you processed in a separate array, and before running your inner loop to count the items, check if he item you're trying to count isn't in your second array already.
Before you print the result, check if you already printed it for this number
Here's my new attempt.
A quick fix (while not the most professional) would be to create another loop checking for repeats right before printing out.
I took your current big loop and turned it into an even bigger monster.
I also tested it out and it works for me. =D
for (int k=0; k< n; k++){
int sum=0;
for (int i=0; i< n; i++)
{
if (a[i]==a[k])
sum= sum+1;
}
bool repeat = false;
for(int i = 0; i < k; i++)
{
if(a[k] == a[i])
{
repeat = true;
}
}
if(!repeat)
cout<< "Number "<< a[k]<<" : "<< sum<< endl;
}
An alternate implementation (and more memory-hungry with your current limit of 20 input values) would be to create an array of 100 "count" values. Increment the appropriate item for each input value, then iterate through the count array outputting non-zero values.
Apparently that description wasn't good enough... perhaps some code would help (NOTE:This code is untested, but should be enough for you to understand the concept):
#include<iostream>
using namespace std;
int main(){
int a[101], n, v;
cout<< "Please enter the number of integers= ";
cin>> n;
cout<<"Please enter"<< n<<" integers: ";
for (int i=0; i<n; i++)
{
cin >> v;
a[v] ++;
}
for (int k=0; k< 100; k++){
if (a[k] > 0)
{
cout<< "Number "<< k + 1 <<" : "<< a[k] << endl;
}
}
}
}
getting familiar with Standart Template Library is the key to writing good programs in my humble opinion, since this is a homework, you do the controlling for 0 and 100 ;-))
#include <iostream>
#include <map>
using std::cin;
using std::map;
using std::cout;
using std::endl;
int main()
{
int limit = 20;
int cnt=0;
int n;
map<int, int> counters;
while( cnt++ < limit )
{
cin >> n;
++counters[n];
}
for(map<int, int>::iterator it = counters.begin();
it!=counters.end(); ++ it)
cout << it->first << " " << it->second << endl;
return 0;
}