Rotating an array:Segmentation Fault (SIGSEGV) - c++

Given an array of N size. The task is to rotate array by d
elements where d is less than or equal to N.
Constraints: 1 ≤ T ≤ 200 1 ≤ N ≤ 200 1 ≤ A[i] ≤ 1000
Example input:
1
5
1 2 3 4 5
2
Output
3 4 5 1 2
The program I wrote seems legit but when I tried to run it is giving me segment fault. I even ran the above example I'm getting the correct output.
The source is GeeksforGeeks: Rotating and Array.
#include <bits/stdc++.h>
using namespace std;
int main() {
int test_case, numb, from, arr[200];
cin >> test_case;
while (test_case--) {
cin >> numb;
for (int i = 0; i < numb; i++) {
cin >> arr[i];
}
cin >> from;
for (int i = from; i < numb; i++) {
cout << arr[i] << " ";
}
for (int j = 0; j < from; j++) {
cout << arr[j] << " ";
}
cout << "\n";
}
return 0;
}
What are the changes which my code needs? What can I do to avoid such errors in the future?click_to_see_segment_fault

Just submitted your exact code on Rotating an Array | Geek for Geeks (site given in the question) . It works perfectly , and no run time error was encountered .

Run the following input and will see weird results. The problem is when the from is greater than the number of elements itself. Basically you need to do a check to see whether the from itself is more than the number of elements or not numb.
#include <bits/stdc++.h>
using namespace std;
int main() {
int test_case, numb, from, arr[200];
cout<<"\nEnter number of test cases:";
cin >> test_case;
cout<<"Test cases = "<<test_case<<endl;
while (test_case--) {
cout<<"Enter count of elements:";
cin >> numb;
cout<<"Count= "<<numb<<endl;
cout<<"Enter the elements:";
for (int i = 0; i < numb; i++) {
cin >> arr[i];
}
cout<<"Entered elements are :";
for (int i = 0; i < numb; i++) {
cout << arr[i]<<" ";
}
cout<<"\nHow many times to rotated? :";
cin >> from;
cout<<"\nRotate it "<<from<<" times:\n";
for (int i = from; i < numb; i++) {
cout << arr[i] << " ";
}
for (int j = 0; j < from; j++) {
cout << arr[j] << " ";
}
cout << "\n";
}
return 0;
}
Lets provide the input as follows:
Enter number of test cases:1
Test cases = 1
Enter count of elements:1
Count= 1
Enter the elements:2
Entered elements are :2
How many times to rotated? :2
Rotate it 2 times:
2 32666
You see the mistake? The location where 32666 is a problem here. It could crash too in your case.

#include <bits/stdc++.h>
using namespace std;
int main() {
int test_case, numb, from, arr[200];
cout<< "Enter the numbe of test cases"<<endl;
cin >> test_case;
if(test_case > 200)
{
cout<<"Number of test cases above limit";
return 0;
}
while (test_case--) {
cout<<"START TEST CASE"<<test_case<<endl;
cout<<"Enter the number of elements in the array"<<endl;
cin >> numb;
if(numb > 200)
{
cout<<"Array size more than expected skipping testcase"<<endl;
continue;
}
cout<<"Enter the elements of array"<<endl;
for (int i = 0; i < numb; i++) {
cin >> arr[i];
}
cout<<"Enter the number of rotations"<<endl;
cin >> from;
if(from > numb || from < 0)
{
cout <<"rotation index out of range skipping testcase"<<endl;
continue;
}
for (int i = from; i < numb; i++) {
cout << arr[i] << " ";
}
for (int j = 0; j < from; j++) {
cout << arr[j] << " ";
}
cout << "\n";
}
return 0;
}
Extending #Charlie's answer,
The program checks for numbs ranges and from's range.

Related

C++ mistake in finding a 'x' number in 2D array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
In my code below, I try to find an 'x' in a 2D array and display its row and column. But it always shows the a[0][1] in the result. Can someone tell me where did I wrong and why is that? I tried other code but there is no difference. Thanks
My code:
#include <iostream>
using namespace std;
int main(){
int m, n, i, j, a[m][n], sum, x, sl=0;
cout<<"insert array number of rows: "; cin>>m;
cout<<"insert array number of columns: "; cin>>n;
for(i=0;i<m;i++){
sum=0;
for(j=0;j<n;j++){
cout<<"insert board["<<i<<"]["<<j<<"]: ";
cin>>a[i][j];
sum+=a[i][j];
}
cout<<"the summary of rows "<<i<<" is: "<<sum<<endl;
}
cout<<"search x= "; cin>>x;
for (i=0; i<=m-1; i++){
for (j=0; j<=n-1; j++){
if (a[i][j]==x){
sl++;
cout<<"x is at "<<"a["<<i<<"]["<<j<<"]"<< endl;
}
}
}
if(sl==0){
cout<<"there is no x in the array";
}
cout<<sl;
return 0;
}
My results:
Sources of error in your code:
You were using a variable length array (which is not a part of C++ standard). Moreover you were setting its rows and columns before even initializing/inputting n and m.
Fixed Code:
#include <iostream>
#include <vector>
using namespace std;
int main() {
int m, n, x, sl = 0;
cout << "Insert number of rows in the array: ";
cin >> m;
cout << "\nInsert number of columns in the array: ";
cin >> n;
// put the below line after cin >> m; cin >> n;
vector<vector<int>> a(m, vector<int>(n, 0)); // <-- Use this instead of int a[m][n];
cout << endl;
for (int i = 0; i < m; ++i) {
int sum = 0;
for (int j = 0; j < n; ++j) {
cout << "\nInsert board[" << i << "][" << j << "]: ";
cin >> a[i][j];
sum += a[i][j];
}
cout << "\nThe sum of the row " << i << " is: " << sum << endl;
}
cout << "\nSearch x = ";
cin >> x;
cout << '\n' << endl;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (a[i][j] == x) {
sl++;
cout << "x is at a[" << i << "][" << j << "]\n";
}
}
}
if (sl == 0) { cout << "\nThere is no x in the array!"; }
else cout << '\n' << sl;
return 0;
}
Sample Input :
2
2
3
4
7
3
3
Sample Output :
Insert number of rows in the array:
Insert number of columns in the array:
Insert board[0][0]:
Insert board[0][1]:
The sum of the row 0 is: 7
Insert board[1][0]:
Insert board[1][1]:
The sum of the row 1 is: 10
Search x =
x is at a[0][0]
x is at a[1][1]
2
For interactive run, you can remove the newline characters at your wish.

How can I make this pyramid with C++ to look like my example?

I would like to create this pyramid with C++, but I am a bit stuck. Can I get some help to complete my example?
6*****
*6****
**6***
***6**
****6*
*****6
int num1;
cout<<"please enter a size between 1-9: "<<flush;
cin>>num1;
for(int i = 0; i < num1; i++)
{
cout <<num1;
for(int j = 0; j <= i; j++)
{
cout<<"*";
}
cout << "\n";
}
6*
6**
6***
6****
6*****
6******
There are two ways you can handle this:
use 2 separate loops, one for the stars in front of the number, and another loop for the stars behind the number, eg:
#include <iostream>
using namespace std;
int main()
{
int num1;
cout << "please enter a size between 1-9: ";
cin >> num1;
for(int i = 0; i < num1; ++i)
{
for(int j = 0; j < i; ++j)
cout << "*";
cout << num1;
for(int j = num1-1; j > i; --j)
cout << "*";
cout << "\n";
}
return 0;
}
Live Demo
use a single loop that conditionally decides whether to output a star or the number depending on which position is currently being output:
#include <iostream>
using namespace std;
int main()
{
int num1;
cout << "please enter a size between 1-9: ";
cin >> num1;
for(int i = 0; i < num1; ++i)
{
for(int j = 0; j < num1; ++j)
{
if (j == i)
cout << num1;
else
cout << "*";
}
cout << "\n";
}
return 0;
}
Live Demo
You need asterisks before the number and after the number. So, let's expand your idea:
int num1;
cout<<"please enter a size between 1-9: "<<flush;
cin>>num1;
for(int i = 0; i < num1; i++)
{
//Asterisks before the number
for(int j = 0; j < i; j++)
{
cout<<"*";
}
cout <<num1;
//Asterisks after the number
for(int j = i; j < num1; j++)
{
cout<<"*";
}
cout << "\n";
}
There is a little improve that you could do: Refactorize in functions:
void writeRow(int length)
{
for (int i = 0; i < length; i++)
std::cout << "*";
}
// Some code...
for(int i = 0; i < num1; i++)
{
//Asterisks before the number
writeRow(i);
cout <<num1;
//Asterisks after the number
writeRow(num1-i);
cout << "\n";
}
You can create the entire string for each row by using the std::string constructor that takes a count and a character.
Basically here is the pattern:
Print 0 stars, the number 6, then num-1 stars.
Print 1 star, the number 6, then num-2 stars.
Print 2 stars, the number 6, then num-3 stars.
etc...
So the pattern is to build a string that consists of the stars before, the number 6, then the stars after, and for each row, you increment the stars before, and decrement the stars after.
So here is an example:
#include <string>
#include <iostream>
int main()
{
int num1 = 6;
int stars_before = 0;
int stars_after = num1 - 1;
for (int i = 0; i < num1; ++i)
std::cout << std::string(stars_before++, '*') << '6' << std::string(stars_after--, '*') << "\n";
}
Output:
6*****
*6****
**6***
***6**
****6*
*****6

User input into array. I am confused with output

Most of the components for the array are in place.
I am however wondering what code is missing for the output to match what I am trying to do.
I tried searching for similar array coding. I would like to call the function and for the user to input numbers up to 20 different inputs.
#define size 20
using namespace std;
int i;
void Input(int student[]) {
for(int i = 0; i < size; i++)
cout << "Enter The Marks of Subject 2 of student no " << i + 1 << " ";
cin >> student[i];
}
void display(int student[]) {
for(int i = 0; i < size; i++)
cout << student[i];
}
int main() {
int student[size];
Input(student );
display(student);
return 0;
In your Input function:
void Input(int student[]) {
for(int i = 0; i < size; i++)
cout << "Enter The Marks of Subject 2 of student no " << i + 1 << " ";
cin >> student[i];
}
You not using brackets, so the cin >> student[i]; is outside of the loop. The i from the for loop is no longer in scope, so you are using the i here:
int i;
Which is never given a value, which leads to undefined behavior. Add brackets:
void Input(int student[]) {
for(int i = 0; i < size; i++) {
cout << "Enter The Marks of Subject 2 of student no " << i + 1 << " ";
cin >> student[i];
}
}

Use C++ to Print a Floyd triangle

I'm trying to build a program which will accept numbers from user and create Floyd triangle.
I tried using the logic of Floyd triangle, but its printing as a line.
Example:
Enter total numbers: 5
Enter the numbers: 3,8,2,4,9
O/p:
3
82
249
Here's my code:
#include <iostream>
using namespace std;
int main()
{
int totalnos, j, i;
cout << "Enter total numbers: ";
cin >> totalnos;
int numbers[totalnos];
cout << "Enter the numbers: ";
for (i = 1; i <= totalnos; i++)
{
cin >> numbers[i];
}
for (i = 1; i <= totalnos; i++)
{
for (j = 1; j <= 1; j++)
{
cout << numbers[i];
}
}
}
You have a problem with the kind of loops shown below. I don't know wether this kind of solution is due to you coming from the Pascal world, or because you've seen it elsewhere. Anyway, you should not make loops start in 1 and go to i, or at least, you should take into account that in the C-like world (C, C++, Java, C#, and many others), arrays start at index 0, and end at index n - 1, being n the size of the array.
int numbers[totalnos];
cout << "Enter the numbers: ";
for (i = 1; i <= totalnos; i++)
{
cin >> numbers[i];
}
The problem is actually not what indexes you use for loops, but that you must always use 0..n-1 when accessing arrays. So you can change your loop to just access the array correctly:
int numbers[totalnos];
cout << "Enter the numbers: ";
for (i = 1; i <= totalnos; i++)
{
cin >> numbers[ i - 1 ];
}
Or you can do as all programmers in the C-like world, and directly start your indexes at 0:
int numbers[totalnos];
cout << "Enter the numbers: ";
for (i = 0; i < totalnos; i++)
{
cin >> numbers[i];
}
Instead of going from 1 to totalnos, now you go from 0 to totalnos - 1 (notice the i < totalnos instead of the i <= totalnos, that's a sutil change).
You were accessing memory past the limit of the array, which means that your program will show undefined behaviour (this means that it will probably crash, though under some conditions, nothing seems to happen, which is even more dangerous).
Now the algorithm itself. I haven't heard about the Floyd triangle. It seems that it is built with the natural numbers starting from 1. However, you are asking for totalnos numbers. You will need more than totalnos numbers in order to build a Floyd triangle with totalnos rows. That's why you need to adjust the position of the number being shown taking into account the number of columns for each row (numPos starts with 0).
cout << endl;
for (i = 0; i < totalnos; i++)
{
if ( ( totalnos - i ) < numPos ) {
numPos = totalnos - i;
}
for (j = 0; j < i; j++)
{
cout << numbers[numPos] << ' ';
++numPos;
}
cout << endl;
}
You can find the whole code here: http://ideone.com/HhjFpz
Hope this helps.
Internal loop can be modified as below :
for (i=0; i < 3; i++)
{
for (j=0; j<=i; j++)
{
cout << numbers[i+j];
}
cout<<" ";
}
Hard coded value "3" can be replaced with the "number of rows of Floyd triangle .
I think this will do the trick .
In inner loop you made mistake with j <= 1; should be j <= i;
And you missed '\n' char for new line.
Here is fix:
#include <iostream>
using namespace std;
int main()
{
int totalnos, j, i, k = 0;
cout << "Enter total numbers: ";
cin >> totalnos;
//int numbers[totalnos];
//cout << "Enter the numbers: ";
// for (i = 1; i <= totalnos; i++)
// {
// cin >> numbers[i];
// }
for (i = 1; i <= totalnos; i++)
{
// your code for (j = 1; j <= 1; j++)
for(j=1; j<=i; ++j) // fixed
cout << k+j << ' ';
++k;
cout << endl; // fix
}
}

how to print an array backwards

The user enteres a number which is put in an array and then the array needs to be orinted backwadrds
int main()
{
int numbers[5];
int x;
for (int i = 0; i<5; i++)
{
cout << "Enter a number: ";
cin >> x;
numbers[x];
}
for (int i = 5; i>0 ; i--)
{
cout << numbers[i];
}
return 0;
}
You're very close. Hope this helps.
#include <iostream>
using namespace std;
int main(int argc, char *argv[]) {
int numbers[5];
/* Get size of array */
int size = sizeof(numbers)/sizeof(int);
int val;
for(int i = 0; i < size; i++) {
cout << "Enter a number: ";
cin >> val;
numbers[i] = val;
}
/* Start index at spot 4 and decrement until k hits 0 */
for(int k = size-1; k >= 0; k--) {
cout << numbers[k] << " ";
}
cout << endl;
return 0;
}
You are very close to your result but you did little mistakes, the following code is the correct solution of the code you have written.
int main()
{
int numbers[5];
int x;
for (int i = 0; i<5; i++)
{
cout << "Enter a number: ";
cin >> numbers[i];
}
for (int i = 4; i>=0; i--)
{
cout << numbers[i];
}
return 0;
}
#include<iostream>
using namespace std;
int main()
{
//get size of the array
int arr[1000], n;
cin >> n;
//receive the elements of the array
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
//swap the elements of indexes
//the condition is just at "i*2" be cause if we exceed these value we will start to return the elements to its original places
for (int i = 0; i*2< n; i++)
{
//variable x as a holder for the value of the index
int x = arr[i];
//index arr[n-1-i]: "-1" as the first index start with 0,"-i" to adjust the suitable index which have the value to be swaped
arr[i] = arr[n - 1 - i];
arr[n - 1 - i] = x;
}
//loop for printing the new elements
for(int i=0;i<n;i++)
{
cout<<arr[i];
}
return 0;
}
#include <iostream>
using namespace std;
int main() {
//print numbers in an array in reverse order
int myarray[1000];
cout << "enter size: " << endl;
int size;
cin >> size;
cout << "Enter numbers: " << endl;
for (int i = 0; i<size; i++)
{
cin >> myarray[i];
}
for (int i = size - 1; i >=0; i--)
{
cout << myarray[i];
}
return 0;
}
of course you can just delete the cout statements and modify to your liking
this one is more simple
#include<iostream>
using namespace std;
int main ()
{
int a[10], x, i;
cout << "enter the size of array" << endl;
cin >> x;
cout << "enter the element of array" << endl;
for (i = 0; i < x; i++)
{
cin >> a[i];
}
cout << "reverse of array" << endl;
for (i = x - 1; i >= 0; i--)
cout << a[i] << endl;
}
answer in c++. using only one array.
#include<iostream>
using namespace std ;
int main()
{
int array[1000] , count ;
cin >> count ;
for(int i = 0 ; i<count ; i++)
{
cin >> array[i] ;
}
for(int j = count-1 ; j>=0 ; j--)
{
cout << array[j] << endl;
}
return 0 ;
}
#include <iostream>
using namespace std;
int main ()
{
int array[10000];
int N;
cout<< " Enter total numbers ";
cin>>N;
cout << "Enter numbers:"<<endl;
for (int i = 0; i <N; ++i)
{
cin>>array[i];
}
for ( i = N-1; i>=0;i--)
{
cout<<array[i]<<endl;
}
return 0;
}