Building a Triangle with c++ loops - c++

I am trying to build a triangle, with a user entered base and height.
When these entered values are different (base!=height), the program goes haywire and gets stuck in the triangle draw loop.
I've tried altering the code a couple of times, but please treat me as a programming novice.
//BUILD TRIANGLE//
#include <string>
#include <iomanip>
#include <iostream>
int main()
{
std::cout << "\nEnter base and height:\n";
int height{0}; int base{0};
std::cin >> base >> height;
std::string bottom(base, '*');
std::string top = "*";
int middlerows = height - 1;
int middlespacechars;
std::cout << top << std::endl;
for (middlespacechars = 0;
middlerows != 1 || middlespacechars != base - 2;
++middlespacechars, --middlerows) {
std::string middlespace(middlespacechars, ' ');
std::cout << "*" << middlespace << "*\n";
}
std::cout << bottom << "\n" << std::endl;
std::cout << "^TRIANGLE\n";
std::cout << "BASE = " << base << std::endl;
std::cout << "HEIGHT = " << height << std::endl;
std::cout << "goodbye" << "\n" << std::endl;
}
The output is totally haywire, with asterisks across the screen in no discernible shape.
When I put in values where base=height, though, a pretty little right angle triangle pops up.

With your code, you can only draw well triangles which have base equal to height.
If you change stop condition in your for loop, you can get what you probably want to get:
for (middlespacechars = 0; middlerows != 1 || middlespacechars != base - 2; ++middlespacechars, --middlerows) {
... into ...
for (middlespacechars = 0; middlerows > 1 || middlespacechars < base - 2; ++middlespacechars, --middlerows) {
It was huge probability that if base and height are different then stop condition will not be achieved. For loop in your code will stop if middlerows will be 1 and middlespacechars will be base - 2 at the same moment.
Test it here.

//C++ program to display hollow star pyramid
#include<iostream>
using namespace std;
int main()
{
int rows, i, j, space;
cout << "Enter number of rows: ";
cin >> rows;
for(i = 1; i <= rows; i++)
{
//for loop to put space in pyramid
for (space = i; space < rows; space++)
cout << " ";
//for loop to print star
for(j = 1; j <= (2 * rows - 1); j++)
{
if(i == rows || j == 1 || j == 2*i - 1)
cout << "*";
else
cout << " ";
}
cout << "\n";
}
return 0;
}

Related

Magic Square confusion

#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std ;
int main()
{
const int maxsize=21 ;
int magq[maxsize][maxsize] ;
int size ;
cout << "Magic Square" << endl ;
cout << "Size (odd): " ;
cin >> size ;
if( size<=0 || size>maxsize)
{
cout << "Size to big" << endl ;
exit(1) ;
}
if( 1!=size%2)
{
cout << "Not an odd nr. " << endl ;
exit(1) ;
}
for( int x=0; x<size; x++)
for( int y=0; y<size; y++)
magq[x][y] = 0 ;
// In the lecture it is said to put the nr. 1 in the first row middle column
int x=(size-1)/2 ;
int y=0 ;
magq[x][y]=1 ; //As we can clearly see here magq[x][y] for i.e size=5 is magq[2][0]
// which is not first row middle column
for( int z=2; z<=size*size; z++)
{
int xneu=(x+1)%size ; // oder: x<size-1 ? x+1 : 0
int yneu=y>0 ? y-1 : size-1 ;
if (0!=magq[xneu][yneu])
{
xneu=x ;
yneu=y+1 ;
if (yneu==size)
{
cout << "Boundary met under?!" << endl ;
yneu=0 ;
}
}
x=xneu ;
y=yneu ;
if( 0!=magq[x][y])
{
cout << "............some meaningless text!" << endl ;
cout << "Nr.: " << z << " Field: " << x << ", " << y << endl ;
exit(1) ;
}
// cout << "Feld " << x << " " << y << " Zahl " << z << endl ;
magq[x][y]=z ;
}
for( int y=0; y<size; y++)
{
for( int x=0; x<size; x++)
cout << setw(5) << magq[x][y] ;
cout << endl ;
}
int diag1=0, diag2=0 ;
for( int i=0; i<size; i++)
{
diag1 += magq[i][i] ;
diag2 += magq[i][size-1-i] ;
}
cout << "Sum: (diag1, diag2, erwartet) "
<< diag1 << " " << diag2 << " " << (size*(size*size+1))/2 << endl ;
return 0 ;
}
Can someone explain to me how is he moving in the matrix, in this exercise?
If we follow his initial notation then for n=5 (for example)
for z=2, xneu=3 and yneu=4, that is totally the reverse of the position 4,3 in which the number 2 should be stored. (Assuming that the index for rows and Column starts from 0 and ends at 4).
Can anyone explain to me, how are we moving in this program?
This program is about creating a magic square according to the "de la Loubère" method. There is a very good explanation on Wikipedia here. Or, because I saw some German text here.
The mechanism is totally simple. Always Go up and right (take boundaries into account). If t´his place is already filled, then go one down.
The links show a step by step example.
Your confusion about the "Middle" comes from the fact that you assume array index 2 to be not the middle. But it is. Array indicess in C++ start wirth 0. So, if you have an odd number and make a integer division by 2, you will always get an even number, because the 0.5 part is truncated.
3/2=1, 5/2=2, 7/2=3 and so on. And with the example of 5, we will receive a 2 which is the middle of indeces 0,1,2,3,4.
This should answer your question.
Additionally, I will show you a different solution
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <array>
// The maximumn dimension of the magic square
constexpr size_t MaxDimension{ 21u };
// Some abbreviations for less typing work. Square will be implemented as a 2 dimensional std::array
using Square = std::array< std::array <int, MaxDimension>, MaxDimension>;
// Create a magic square following the method of "De-la-Loubère"
void createMagicSquare(Square& square, int sizeOfSquare) {
// Reset all values in the square to 0
square = {};
// Starting row and column. Set to upper middle cell
int row{}; int column{ sizeOfSquare / 2};
// This will wrap a position if it leaves the boundary of the square
auto wrap = [&sizeOfSquare](const int position) { return (position + sizeOfSquare) % sizeOfSquare; };
// Now build the magic square and fill it with all numbers
for (int runningNumber{ 1 }; runningNumber <= (sizeOfSquare * sizeOfSquare); ++runningNumber) {
// Write number into cell at current position
square[row][column] = runningNumber;
// If the upper right cell is occupied
if (square[wrap(row-1)][wrap(column+1)] != 0) {
// Then just go one rowe down
row = wrap(row + 1);
}
else {
// Next position will be upper right
row = wrap(row - 1);
column = wrap(column + 1);
}
}
}
// Output of the magic square
void display(Square& square, int sizeOfSquare)
{
constexpr int Width = 4;
std::cout << "\nThe Magic square is: \n\n";
for (int row = 0; row < sizeOfSquare; ++row) {
for (int column = 0; column < sizeOfSquare; ++column)
std::cout << std::setw(Width) << square[row][column];
std::cout << "\n\n";
}
}
int main()
{
// Give instruction what to do
std::cout << "Enter The Size of the Magic Square (odd number (<=21): ";
// Read user inpuit and make sure that it is a correct value
if (int sizeOfSquare{}; (std::cin >> sizeOfSquare) and (sizeOfSquare <= MaxDimension) and (sizeOfSquare%2)) {
// Define the empty square
Square square{};
// Fill it with magic numbers
createMagicSquare(square, sizeOfSquare);
// Show result
display(square, sizeOfSquare);
}
else std::cerr << "\nError: Wrong Input\n";
}

C++ Checking while condition with user input array

I'm student in high school and I wanna to make simple game with guessing random number and I had problem with user inputed array while I need to check the condition.
When it comes to checking condition it says there wasn't declared i.
Below I leave code.
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main()
{
int PlayerAns[200];
int iNumSecret, iNumGuess;
int iWrongAns = 0;
srand(time(NULL));
int iNumMax = 100;
iNumSecret = rand() % iNumMax + 1;
cout << "========== Simple Game =========== "
<< "\n";
do
{
for (int i = 0; i < 100; i++)
{
cout << "Guess the number od 1 do " << iNumMax << "\n";
cin >> PlayerAns[i];
if (iNumSecret < PlayerAns[i] && PlayerAns[i] >= 0 && PlayerAns[i] <= 100)
{
cout << " - Secret number is lower ! "
<< "\n";
}
else if (iNumSecret > PlayerAns[i] && PlayerAns[i] >= 0 && PlayerAns[i] <= 100)
{
cout << " - Secret number is higher ! "
<< "\n";
}
else if (PlayerAns[i] < 0 || PlayerAns[i] > 100)
{
cout << " - Number is out of scope ! "
<< "\n";
iWrongAns++;
}
}
}
while (iNumSecret != PlayerAns[i]);
{
cout << "--- You get it !!!"
<< "\n";
cout << PlayerAns << "\n";
cout << "You guess number out of scope that many times: " << iWrongAns << "\n";
}
return 0;
}
The variable i is defined only inside the for loop in that case.
If you wanted to, you can define i before the do while loop, and then use it in the for loop like so:
for(i = 0; i < 100; i++) {
...
}
Suggestion:
You can try not using the for loop and make the PlayerAns an integer instead of an array.

how I can print an array as a vector form

I want to cout an array as a row vector but when I write:
int main() {
int B[3]={0};
for (int w = 0; w <2; w++) {
cout <<"B="<<" "<< B[w] << " ";
}
cout << endl;
return 0;
}
The output is B=0 B=0
But I want output to be like:
B=(0 0)
For a fixed size array of only I would probably even prefer a oneliner like this, because I can read it at first glance:
cout << "B=(" << B[0] << " " << B[1] << " " << B[2] << ")\n";
For a container B with a dynamic or very high number of elements n, you should probably do something like this:
cout << "B=(";
if(n > 0)
{
cout << B[0];
// note the iteration should start at 1, because we've already printed B[0]!
for(int i=1; i < n; i++)
cout << ", " << B[i]; //I've added a comma here, so you get output like B=(0, 1, 2)
}
cout << ")\n";
This has the advantage, that no matter what number of elements, you don't end up with trailing commas or unwanted whitespace.
I'd reccommend making a generic (template) function for the purpose of printing array/std::vector content anyways - it's really useful for debugging purposes!
int main() {
int B[3] = { 0 };
cout << "B=(";
for (int w = 0; w < 3; w++) {
cout << B[w];
if (w < 2) cout << " ";
}
cout << ")" << endl;
return 0;
}
Output should be now:
B=(0 0 0)
The simplest way to do this is:-
#include<iostream>
using namespace std;
int main()
{
int B[3]={0};
cout << "B=(";
for (int w = 0; w < 3; w++)
{
cout << B[w] << " ";
}
cout << ")" << endl;
return 0;
}
the output will be B= (0 0 0 )
You can try this one if you want:
#include <iostream>
using namespace std;
int main() {
int B[3]={0};
cout << "B=(";
for (int w = 0; w <2; w++) {
cout << B[w];
if(w != 1) cout << " ";
}
cout << ")" << endl;
cout << endl;
return 0;
}
The output is:
B=(0 0)
The line if(w != 1) checks whether you 've reached the last element of the array. In this case the last index is 1, but in general the if statement should be: if(w != n-1) where n is the size of the array.

issue with while loops

#include <iostream>
#include <math.h>
using namespace std;
int main() {
int arrowBaseHeight = 0;
int arrowBaseWidth = 0;
int arrowHeadWidth = 0;
int i = 0;
int j = 0;
cout << "Enter arrow base height:" << endl;
cin >> arrowBaseHeight;
cout << "Enter arrow base width:" << endl;
cin >> arrowBaseWidth;
cout << "Enter arrow head width:" << endl;
cin >> arrowHeadWidth;
cout << endl;
// Draw arrow base
while (i <= arrowBaseHeight){
while (j <= arrowBaseWidth){
cout << "*";
j++;
}
cout << endl;
j = 0;
i++;
}
// Draw arrow head (width = 4)
return 0;
}
I am trying to write a simple program that takes 3 user entered integers and assigns them to arrowBaseHeight, arrowBaseWidth, and arrowHeadWidth. The output should be a series of asterisks (*) that print out like:
**
**
**
****
***
**
*
to create an image of an arrow.
I have been trying to figure out the best way to print out the base portion of the arrow using nested loops (I have been using while but if for is better, let me know). I have tried multiple different ways and I have yet to figure one out that doesn't throw back an error. I have yet to get to the arrow head portion but if anyone wants to point me in the right direction, it would be helpful!
You were close, but if you want for a loop to be executed exactly n times, starting your counter i at 0, the condition should be i < n, not i <= n.
About the head, you just have to decrement the number of characters printed in every line, starting from the inputted width.
#include <iostream>
int main()
{
using std::cout;
using std::cin;
int arrowBaseHeight = 0;
cout << "Enter arrow base height:\n";
cin >> arrowBaseHeight;
int arrowBaseWidth = 0;
cout << "Enter arrow base width:\n";
cin >> arrowBaseWidth;
int arrowHeadWidth = 0;
cout << "Enter arrow head width:\n";
cin >> arrowHeadWidth;
cout << '\n';
// Draw arrow base
for ( int i = 0; i < arrowBaseHeight; ++i )
{
for ( int j = 0; j < arrowBaseWidth; ++j )
{
cout << '*';
}
cout << '\n';
}
// Draw arrow head
for ( int i = 0, width = arrowHeadWidth; i < arrowHeadWidth; ++i, --width )
{
for ( int j = 0; j < width; ++j )
{
cout << '*';
}
cout << '\n';
}
return 0;
}
You can see a lot of repeated code, consider refactoring it using some custom functions, instead.
You should change the condition of the while loops to:
while (i < arrowBaseHeight) and
while (j < arrowBaseWidth).
And for the arrowHeadWidth you could try to get the middle of the arrowBaseHeight. Maybe like this
int r = 0;
if(i == arrowBaseHeight / 2)
{
while(r < arrowHeadWidth)
{
cout << "*";
r++;
}
}
I haven't tested it. I hope it helps.
All you need to do is to add a new variable which could indicate what are you need to print right now.
The rule is :
If: up to half of "arrowBaseHeight" iteration you need to print the base
Else: print the head and after that decrease in 1
In addition finger rule - if you are using "while" and you need to increase an iterator it always indicate that you need to use For
#include <iostream>
#include <math.h>
using namespace std;
int main() {
int arrowBaseHeight = 0;
int arrowBaseWidth = 0;
int arrowHeadWidth = 0;
int newArrowBaseWidth=0;
cout << "Enter arrow base height:" << endl;
cin >> arrowBaseHeight;
cout << "Enter arrow base width:" << endl;
cin >> arrowBaseWidth;
cout << "Enter arrow head width:" << endl;
cin >> arrowHeadWidth;
cout << endl;
// Draw arrow base
for(int i=0; i < arrowBaseHeight; i++){
newArrowBaseWidth= i < arrowBaseHeight/2 ? arrowBaseWidth : arrowHeadWidth--;
for(int j=0; j < newArrowBaseWidth; j++){
cout << "*";
}
cout << endl;
}
// Draw arrow head (width = 4)
return 0;
}
Another thing is if you want to iterate n time you need to change the condition from =< that here mean - n+1 time, to <

Draw A Rectangle With Asterisks

I am trying to write a C++ Program to display a rectangle drawn in asterisks. I have the program running properly except for the fact that only one side of the heights of my rectangles print. Here is the code I have currently written for the display rectangle method.
void Rectangle::displayRectangle()
{
int i=0, j=0;
for (int i = 0; i < width; i++)
{
cout << "*";
}
cout << endl;
for (int i = 0; i < height - 2; i++)
{
cout << "*";
for (int j = 0; j < width; j++)
{
cout << " ";
}
cout << endl;
}
for (int i = 0; i < width; i++)
{
cout << "*";
}
cout << endl;
}
Specify a width and height at the start then you only need 3 loops. The first will print the top line of the rectangle. The second will print both sides of the rectangle (minus the very top and very bottom of the sides). The third will print the bottom line of the rectangle.
Like so
// Width and height must both be at least 2
unsigned int width = 7; // Example value
unsigned int height = 5; // Example value
// Print top row
for(unsigned int i = 0; i < width; i++);
{
std::cout << "*";
}
std::cout << std::endl;
// Print sides
for(unsigned int i = 0; i < height - 2; i++)
{
std::cout << std::setw(width - 1) << std::left << "*";
std::cout << "*" << std::endl;
}
// Print bottom row
for(unsigned int i = 0; i < width; i++)
{
std::cout << "*";
}
std::endl;
You will need to include both iostream and iomanip for this to work (setw is part of iomanip).
The top and bottom rows could also be done using the method to fill spaces with a given character, but I cannot recall that method right now.
This can be done much easier and clearer.
The logic here is to draw from line to line, so you only need one loop
(I chose to use the auto specifier in this example because I think it looks neater and used often in modern c++, if your compiler doesn't support c++11, use char, int etc.):
int main()
{
using namespace std;
auto star = '*';
auto space = ' ';
auto width = 20;
auto height = 5;
auto space_cnt = width-2;
for (int i{0}; i != height+1; ++i) {
// if 'i' is the first line or the last line, print stars all the way.
if (i == 0 || i == height)
cout << string(width, star) << endl;
else // print [star, space, star]
cout << star << string(space_cnt, space) << star << endl;
}
}
Well, you don't see the second vertical line, because you don't draw it in your line loop.
void DrawRect(int w, int h, char c)
{
cout << string(w, c) << '\n';
for (int y = 1; y < h - 1; ++y)
cout << c << string(w - 2, ' ') << c << '\n';
cout << string(w, c) << '\n';
}
Try to prompt the user for the number of rows and columns. Then, using nested loops, display a rectangle of stars based on the user input.