I am coding an Inversed pyramid console application, when you enter a number, For example 3, It'll output it with the number of staircase,
*****
***
*
It works and everything is fine but when it outputs the pyramid. It keeps spamming spaces till the program crashes. Here's the source code:
Note: This is a recursion project.
#include <iostream>
using namespace std;
int Pyramid(int n, int index)
{
if(index > n) //Base Case
{
return 0;
}
for(int i=index+1; i<=n; i++)
{
cout<<" ";
}
for(int j=1; j<index*2; j++)
{
cout<<"*";
}
cout<<endl;
return Pyramid(n, index-1);
}
int main()
{
int n;
cin>>n;
Pyramid(n, n);
return 0;
}
Can anyone help me fix this problem and keep it a recursion project?
Your stop condition in your recursion is wrong.
Here is what I did and it displays the star pyramid correctly
int Pyramid(int n, int index)
{
// your stop condition is wrong (not index>n but index ==0)
if (index ==0 )
{
return 0;
}
//until here
for(int i=index+1; i<=n; i++)
{
cout<<" ";
}
for(int j=1; j<index*2; j++)
{
cout<<"*";
}
cout<<endl;
return Pyramid(n, index-1);
}
An example execution is as follows:
10
*******************
*****************
***************
*************
***********
*********
*******
*****
***
*
if(index > n) //Base Case
{
return 0;
}
This seems not correct. You start index with n, and index will always be decremented. index > n will never be reached.
Related
This is what I wrote so far, where did I go wrong?
#include <iostream>
using namespace std;
int main()
{
int x[5], count=0;
for (int i=0;i<5;i++)
cin>>x[i];
for (int i=0;i<5;i++)
{
for (int n=2;n<x[i];n++)
{
if (x[i]%n==0)
count++;
}
if (count==1)
cout<<x[i]<<" ";
}
}
Edit:
Many thanks to everyone that tried to help. The problem was that I had to int count in the loop so that it would start from 0 every time. Here's my new working code:
#include <iostream>
using namespace std;
int main()
{
int x[5];
for (int i=0;i<5;i++)
cin>>x[i];
for (int i=0;i<5;i++)
{ int count=0;
for (int n=2;n<=x[i];n++)
{
if (x[i]%n==0)
count++;
}
if (count==1)
cout<<x[i];
}
}
#include <iostream>
using namespace std;
int main()
{
int x[5], count=0;
for (int i=0;i<5;i++)
cin>>x[i];
for (int i=0;i<5;i++)
{
bool check = true;
for (int n=2;n<x[i];n++)
{
if (x[i]%n==0)
{
check = false;
break;
}
}
if (check)
cout<<x[i]<<" ";
}
}
For better complexity, change your nested for loop to :
for (int n=2;n<=sqrt(x[i]);n++)
Other way :
int main ()
{
for (int i=2; i<100; i++)
{
bool check=true;
for (int n=2; n*n<=x[i]; n++)
{
if (x[i] % n == 0)
{
check=false;
break;
}
}
if(check) cout << x[i] << " ";
}
return 0;
}
Here's my solution.
I basically assume all numbers are prime, but if I find them not to be prime I don't print them out.
int main() {
bool primeNumber;
int length = 0;
int x[5], count=0;
for (int i=0;i<5;i++){
length++;
cin>>x[i];
}
for (int i = 0; i < length; i++ )
{
primeNumber = true;
for (int j = 3; j <= x[i]/2; j += 2 )//Not necessary to check agains numbers higher than half the number you want to check
{
if (x[i] % j == 0)
{
primeNumber = false;
}
}
if(primeNumber){cout << "Primenumber: " << x[i] << endl;}
}
}
EDIT:
Here's a comment on your code
Let's say your array looks like this
{5,9,13,15, 17}
int main()
{
int x[5], count=0;
for (int i=0;i<5;i++)
cin>>x[i];
for (int i=0;i<5;i++)
{
for (int n=2;n<x[i];n++)
{
Here you loop from 2-4(2,3,4). It's only necessary to loop half the number you want to check. e.g. (x[i]/2), but you can do it like you have done here.
if (x[i]%n==0){
count++;}
When your number is 5 and you check agains n numbers This will produce 5%2=1,5%3=2,5%4=1. But 5 is a prime number and your code didn't manage to detect that.
}
if (count==1)
Let's say you did find that 5 is a prime above and you managed to increment count to 1. What happens when you find another prime number in your array e.g. 7. That will make count be equal to 2. But you only check against 1, so therefor your next prime number doesn't get printed because count will only be equal to 1 after the first prime number and not the rest.
cout<<x[i]<<" ";
}
}
Hopefully you understood my explanation. It always helps to go over your code by hand or debug mode and think what the code will do with different numbers.
All numers are divideable by itself. That will make all numbers prime if you try to divide numbers with themselves
I have written a program to print the matrix in the spiral form, but it only works for 3*3. how to make it useful for all the dimensions.
#include<iostream.h>
#include<conio.h>
void main()
{
int i,j,k=1,l=0;
int n;
clrscr();
cout<<"Enter the number of row : ";
cin>>n;
int a[3][3];
cout<<"Matrix Form : "<<"\n";
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
a[i][j]=i*n+(j+1);
cout<<a[i][j]<<"\t";
}
cout<<"\n";
}
cout<<"Spiral form"<<"\n";
for(i=k;i<n;i++)
{
cout<<a[k][i]<<"\t";
}
k++;
for(i=k;i>=0;i--)
{
cout<<a[k][i]<<"\t";
}
k--;
for(i=k;i>=0;i--)
{
cout<<a[i][l]<<"\t";
}
for(i=k;i<n;i++)
{
cout<<a[l][i]<<"\t";
}
getch();
}
Assuming the code is working, you need to act on this row:
int a[3][3];
The easiest way is using C++ std::vector:
std::vector<std::vector<int> > a(n, std::vector<int>(n));
Remember to #include <vector> as well.
I tried to generate 3*3 spiral matrix using c by using increment and decrement of rows and columns in an array,then found out sum of main and opposite diagonals of the matrix.
My code is as follows
#include<stdio.h>
#define n 3
int main()
{
int m=n/2,i,j,a[10][10],c=1,sum=0,s=0;
for(i=m,j=m;j<n;j++)
{
a[i][j]=c;
c++;
}
j--;
i++;
while(j>=0)
{
a[i][j]=c;
c++;
j--;
}
i--;
j++;
a:
if(i>=0)
{
a[i][j]=c;
c++;
i--;
goto a;
}
i++;
j++;
b:
if(j<n)
{
a[i][j]=c;
c++;
j++;
goto b;
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("\t%d",a[i][j]);
}printf("\n");
}
for (i = 0; i <n; i++)
{
sum = sum + a[i][i];
s=s+a[i][n-i-1];
}
printf("sum of diagonals is d1: %d d2: %d d1+d2: %d",sum,s,s+sum);
return 0;
}
output:
click here to view output
I am trying to implement a simple merge sort for even number of elements using the following code :
#include <iostream>
using namespace std;
void merge(int arr1[10],int len1,int arr2[10],int len2,int arr3[10],int len3)
{
int i,j,k;
while(i<len1&&j<len2&&k<len3)
{
if(arr1[i]<arr2[j])
{
arr3[k] = arr1[i];
i++;k++;
}
else if(arr1[i]>arr2[j])
{
arr3[k] = arr2[j];
k++;
j++;
}
}
}
void mergeSort(int a[10],int n)
{
int arr1[10],arr2[10];
for(int i=0;i<n/2;i++)
{
arr1[i] = a[i];
}
for(int i=(n/2+1);i<n;i++)
{
arr2[i] = a[i];
}
mergeSort(arr1,n/2);
mergeSort(arr2,n/2);
merge(arr1,n/2,arr2,n/2,a,n);
}
int main() {
int arr[10],n;
cout << "Enter number of elements\n";
cin >> n;
cout<<"Enter elements\n";
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
mergeSort(arr, n);
cout<<"Sorted array is"<<endl;
for(int i=0;i<n;i++)
{
cout<<arr[i]<<endl;
}
return 0;
}
But I am getting a EXC_BAD_ACESS error on the opening brace of the mergeSort() method. I am new to Xcode and not sure on how to fix this. How do I fix this ?
Thanks !
You have forgot to initialize the int variables i, j, k to 0 (zero) in the function definition for merge(...).
void merge(int arr1[10],int len1,int arr2[10],int len2,int arr3[10],int len3)
{
// int i,j,k; // Not initialized.
int i = j = k = 0;
while(i<len1&&j<len2&&k<len3)
{
...
...
}
After Edit:
void mergeSort(int a[10],int n)
{
int arr1[10],arr2[10];
for(int i=0;i<n/2;i++)
{
arr1[i] = a[i];
}
// Here you are skipping the middle index.
// Let's say array is of length 10, then arr1 contains elements on index from 0 to 4 (5 elements),
// whereas arr2 contains elements on index from 6 to 9 (4 elements).
// 5th index element is missing.
// for(int i=(n/2+1);i<n;i++)
for(int i=(n/2);i<n;i++)
{
arr2[i] = a[i];
}
mergeSort(arr1,n/2);
mergeSort(arr2,n/2);
merge(arr1,n/2,arr2,n/2,a,n);
}
Hope it helps!
#include <iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
int n,m,counter=0;;
cin>>n>>m;
char x[n][m];
int y[n][m];
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
cin>>x[i][j]; //array input
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
counter=0;
if(x[i][j]=='.') // searching for mines(*)
{
if (x[i][j-1]=='*')
counter++;
if (x[i][j+1]=='*')
counter++;
if (x[i-1][j]=='*')
counter++;
if (x[i+1][j]=='*')
counter++;
if (x[i+1][j-1]=='*')
counter++;
if (x[i+1][j+1]=='*')
counter++;
if (x[i-1][j-1]=='*')
counter++;
if (x[i-1][j+1]=='*')
counter++;
}
if(x[i][j]!='*')
y[i][j]=counter; // assign values
else
y[i][j]='*';
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(y[i][j]==42)
cout<<'*';
else
cout<<y[i][j]; // output numeric array
}
cout<<endl;
}
return 0;
}
This is Minesweeper code which has input like
4 4
*...
....
.*..
....
and output
*100
2210
1*10
1110
But the code's output is
*101
2210
1*10
1110
the zero on the top right turn into 1 What's making it do that ?
and is there an more easy way to search for the mines(*) without all the if conditions ?
You are reading beyond array's memory. While you're on lines 0..n-2, you're reading next line's chars, at line n-1 you're reading inaccessible memory.
You have to check that memory you access belongs to proper lines and are within array bounds.
I.e.
if (x[i][j+1]=='*')
What if j == m - 1?
if (x[i-1][j]=='*')
What if i == 0?
There are basically two fixes to this problem.
First, you can each time check that i, j are in bounds, say
if (j < m - 1 && x[i][j+1]=='*')
That will solve the problem, but is bad from code reuse perspective. I'd write a function, say
char get_at(char ** array, int i, int j, int n, int m)
{
if (i >= 0 && i < n && j >= 0 && j < m)
return array[i][j];
else
return '!';
}
This function returns '!' if indices are out of bounds, so it will not be interpreted as a mine.
I am trying to point something out in your code:
int main()
{
int n,m,counter=0;;
cin>>n>>m;
char x[n][m];
int y[n][m];
/**
* Minesweeper solving has always worked (if followed step-wise) is
* scanning the neihbouring 8 cells i.e.
* top(left,middle,right),side(left,right), and
* bottom(left,middle,right). You probably should try and follow this
* in your code so that any indexing issues can be avoided
*
*
* BTW - don't forget the corners/edges
*
*/
for(int i=0;i<n;i++) // This is a bit dangerous what if the index is -1?
{
for(int j=0;j<m;j++) // Same indexing issue here.
{
cin>>x[i][j];
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
counter=0;
if(x[i][j]=='.') // If current pos is '.'
{
if (x[i][j-1]=='*')
counter++;
if (x[i][j+1]=='*')
counter++;
if (x[i-1][j]=='*')
counter++;
if (x[i+1][j]=='*')
counter++;
if (x[i+1][j-1]=='*')
counter++;
if (x[i+1][j+1]=='*')
counter++;
if (x[i-1][j-1]=='*')
counter++;
if (x[i-1][j+1]=='*')
counter++;
}
if(x[i][j]!='*') // If current pos is ANYTHING but '*', may be you want ELSE_IF condition?
y[i][j]=counter;
else
y[i][j]='*';
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(y[i][j]==42)
cout<<'*';
else
cout<<y[i][j];
}
cout<<endl;
}
return 0;
}
Is that what you are actually thinking?
I wanted to make a pyramid like this:-
____*
___*_*
__*___*
_*_____*
*********
for n=5.
the lines are not underscores but spaces.
My try:-
#include <iostream.h>
void main()
{ int i,k,l,n;
cin>>n;
for(i=1; i<=n-1; i++)
{
for(k=1; k<=i; k++)
{if((k==n+i-1)||(k==n-i+1))
cout<<"*";
else
cout<<" ";
}
cout<<"\n";
}
for(l=1; l<=2*n-1; l++)
cout<<"*";
}
But the output comes as:-
__ *
_*
Note: This is a turbo c++ program.
UPDATE:
With some optimization and by taking n as row count instead of base width, we have something very simple:
void drawPyramid(const int &n) {
int b=2*n-1;
for (int i=b/2; i>=0; i--) {
for (int j=0;j<b-i; j++) {
if (i==0 || j==i || j==b-i-1) {
std::cout<<"*";
} else {
std::cout<<" ";
}
}
std::cout<<std::endl;
}
}
Old:
It was quite funny to do, but it works as well. My approach is to start a counter from the maximum width that the pyramid may have at the end, then divide the problem into two distinct steps:
Go to the first edge
Go to the second edge
It sure can be optimized but it will give you the idea:
int drawPyramid(const int &baseWidth, const char &edgeChar, const char &outsideChar, const char &insideChar) {
// test if base width allows to have a single char at the top of it
if (baseWidth%2==0) {
std::cout<<"Error in 'drawPyramid(const int &baseWidth)': Pyramid base width must be an odd number for the top to match"<<std::endl;
return 0;
}
for (int i=baseWidth; i>=0; i-=2) { // the first edge is initially far, then gets closer
int j=0;
// Go to first edge
while (j<i/2) {
std::cout<<outsideChar;
j++;
}
std::cout<<edgeChar;
if (i==1) { // at the bottom of the pyramid
for (int k=0; k<baseWidth-1; k++) {
std::cout<<edgeChar;
}
} else if (i<baseWidth) { // test if there is a second edge to reach
// Go to second edge
while (j<baseWidth-i/2-2) {
std::cout<<insideChar;
j++;
}
std::cout<<edgeChar;
}
// Done with the current line
std::cout<<std::endl;
}
return 1;
}
Hope this helps :)
modify your loop to this and it works
for(i=1; i<=n-1; i++)
{
for(k=1; k<i + n; k++) // greater range than previously to include whole triangle
{if((k==n+i-1)||(k==n-i+1)) // == instead of --
cout<<"*";
else
cout<<" ";
}
cout<<"\n";
}
for(l=1; l<=2*n-1; l++)