I am unable to output a pyramid in C++ - c++

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++)

Related

Why my C++ Recursion Program keeps on forever

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.

Calculate the hourglass sum for every hourglass in a 6 by 6 matrix(where the entries can only be from 0 to 9) then print the maximum hourglass sum

What is wrong with this code?
#include <bits/stdc++.h>
using namespace std;
int main()
{
int a=0;int b=0;
vector<vector<int>> arr(6);
for (int i = 0; i < 6 ; ++i) {
arr[i].resize(6);
for (int j = 0; j < 6; ++j) {
cin >> arr[i][j];
}
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
{
a=arr[i][j]+arr[i][j+1]+arr[i][j+2]+arr[i+1][j+1]+arr[i+2][j]+arr[i+2][j+1]+arr[i+2]
[j+2];
}
if(a>b){
b=a;
a=0;
}
else{
a=0;
}
}
cout<<b;
return 0;
}
The left bottom most hourglass is not considered in this code, it is working well in all the other parts. can you tell me the mistake here?
the left bottom most hourglass is not considered in this code, it is working well in all the other parts.
No, not only the left bottom most hourglass is not considered, but rather all hourglasses except the last from each row aren't. That's because the hourglass sum a is only compared to the current maximum b after the loop for the columns in a row, so only the last sum is considered. To correct this, you can change
{
a=arr[i][j]+arr[i][j+1]+arr[i][j+2]+arr[i+1][j+1]+arr[i+2][j]+arr[i+2][j+1]+arr[i+2]
[j+2];
}
if(a>b){
b=a;
a=0;
}
else{
a=0;
}
to
{
a=arr[i][j]+arr[i][j+1]+arr[i][j+2]+arr[i+1][j+1]+arr[i+2][j]+arr[i+2][j+1]+arr[i+2][j+2];
if (a>b) b=a;
}

Trying to create a program that reads an array and prints the prime numbers

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

Having trouble compiling my first c++ program

Here is my code:
#include<iostream>
private int chessBoard[8][8];
void printBoard(int board[][])
{
for(int i=0; i<8; i++)
{
for(int j=0; j<8; j++)
{
if(board[i][j])
{
cout<<"Q ";
}
else
{
cout<<"* ";
}
}
cout<<endl;
}
}
//This method will check if any queens are in attacking position to the left of the test queen placement
bool checkSpot(int board[][],int row, int col)
{
bool safe = true;
//checks the current row for queens
for(int i=0; i<col, i++)
{
if(board[row][i])
safe=false;
{
//checks the upper diag
for( int i=row, int j=col; i>0 && j>0; i--, j--)
{
if(board[i][j])
safe=false;
}
//checks lower diag
for(int i = row, int j=col; i<8 && j>0; i--, j++)
{
if(board[i][j])
safe=false;
}
if(safe)
{
return true;
}
else
return false;
}
bool solve(int board[][], int testCol)
{
bool solved = false;
bool safe;
if(testCol==8)
{
solved = true;
return solved;
}
for(int i =0; i>8; i++)
{
// test if the tested column(testCol) and the row(i) are both safe for the queen to be placed at then we can move into placing said queen and more onto the next column for
// more solutions in this same method recursivly
safe = checkSpot(board, i, testCol);
if(safe)
{
//place the queen
board[i][col]=1;
//recursion to go back through this method in the next column
if(solve(board[][], testCol+1)
{
solved = true;
printBoard(board)
return solved;
}
else
{
//if the queen cannot be placed, we have to remove the previous queens and move them until a solution is found.
board[i][testCol]=0;
}
}
}
int main()
{
solve(chessBoard, 0);
}
There errors i continue to get are as follows:
8queens.cpp:3:17: error: variable or field ‘printBoard’ declared void
void printBoard(board[][])
^
8queens.cpp:3:17: error: ‘board’ was not declared in this scope
8queens.cpp:3:23: error: expected primary-expression before ‘]’ token
void printBoard(board[][])
^
8queens.cpp:3:25: error: expected primary-expression before ‘]’ token
void printBoard(board[][])
The logic of this was pretty simple(at least i hope it works well) but i cant even get past the compiler. Can I get a little guidance on this problem?
You were all a huge help, but sadly i found out that I can only use 1d arrays for this problem so I had to start from scratch. Again thank you all for the help, your advice will definitely help me in the future.
Well, there are many errors in your code. Lets look at them.
First of all, remove that private from
private int chessBoard[8][8];
you need to use private only on the members of classes . So change it to
int chessBoard[8][8];
Next, in all your functions, you have something like
void printBoard(int board[][])
^
here, it's wrong
You need to provide the size, you can only skip the first size, all the rest must be provided so better to change it to
void printBoard(int board[][8])
^
it's okay to leave this one
make that change to all of your functions.
You are also missing a few } in some places of your code.
Nearly forgot, you need to either add a
using namespace std;
right after the headers, or use
std::cin
std::cout
and
std::endl
instead of cin , cout and endl .
You also have
for(int i=0; i<col, i++)
^
you need a semicolon here
And also
for( int i=row, int j=col; i>0 && j>0; i--, j--)
^
no need for another int here
just change that to
for( int i=row, j=col; i>0 && j>0; i--, j--)
This compiles. As to what I did, there was a lot and it would take awhile to write each thing down. One major thing to pay attention to is the for loops.
You have:
for( int i=row, int j=col; i>0 && j>0; i--, j--)
{
if(board[i][j])
safe=false;
}
When you want to do a nested for loop, do this:
for (int i = row; i > 0; i--)
{
for (int j = col; j > 0; j--)
{
if (board[i][j])
safe = false;
}
}
Also, pay attention to your brackets {} () as they were inconsistent and some were missing.
For arrays, you must specify at least one dimension when using a 2d array.
You had: int board[][] in various places. You must have: int board[][8] instead.
Also, if you want to use cout, endl, cin, etc... You must have include namespace std; otherwise you will have to use: std::cout, std::endl, std::cin.
But anyway, this should compile now.
#include<iostream>
using namespace std;
int chessBoard[8][8];
void printBoard(int board[][8])
{
for (int i = 0; i<8; i++)
{
for (int j = 0; j<8; j++)
{
if (board[i][j])
{
cout << "Q ";
}
else
{
cout << "* ";
}
}
cout << endl;
}
}
//This method will check if any queens are in attacking position to the left of the test queen placement
bool checkSpot(int board[][8], int row, int col)
{
bool safe = true;
//checks the current row for queens
for (int i = 0; i < col; i++)
{
if (board[row][i])
safe = false;
{
//checks the upper diag
for (int i = row; i > 0; i--)
{
for (int j = col; j > 0; j--)
{
if (board[i][j])
safe = false;
}
}
//checks lower diag
for (int i = row; i < 8; i--)
{
for (int j = col; j > 0; j++)
{
if (board[i][j])
safe = false;
}
}
if (safe)
{
return true;
}
else
return false;
}
}
}
bool solve(int board[][8], int testCol)
{
bool solved = false;
bool safe;
if (testCol == 8)
{
solved = true;
return solved;
}
for (int i = 0; i > 8; i++)
{
// test if the tested column(testCol) and the row(i) are both safe for the queen to be placed at then we can move into placing said queen and more onto the next column for
// more solutions in this same method recursivly
safe = checkSpot(board, i, testCol);
if (safe)
{
//place the queen
board[i][testCol] = 1;
//recursion to go back through this method in the next column
if (solve(board, testCol + 1))
{
solved = true;
printBoard(board);
return solved;
}
else
{
//if the queen cannot be placed, we have to remove the previous queens and move them until a solution is found.
board[i][testCol] = 0;
}
}
}
}
int main()
{
solve(chessBoard, 0);
}

Minesweeper Code error

#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?