Input number, then print stairs vertically mirrored - c++

as in the title.
I could do the easier one, just print them normally, but I have no clue how to mirror them. Here's my code for the "backwards" stairs.
int szam;
cin >> szam;
for (int i = 0; i < szam; i++) {
for (int j = 0; j <= i; j++) {
cout << "*";
}
cout << endl;
}
So when the input number is 4, It's printing this,
*
**
***
****
but i need them mirrored vertically, like this
*
**
***
****
Thanks for the help in advance, and I'd appreciate if you would explain what why happened.

This just comes down to arithmetic, really.
Study the shape again.
Now pretend you're not "mirroring" it, but just adding some whitespace to the start of each line. Because, really, you are.
How much whitespace? It starts at 3 for the first line (i=0) and ends at 0 for the last line (i=3). What's the pattern there?
When we work it out, it comes to szam-1+1 spaces.
Now we can just add those spaces, which is easy:
int szam;
cin >> szam;
for (int i = 0; i < szam; i++) {
// This loop is new
for (int j = 0; j < szam-1+1; j++) {
cout << ' ';
}
for (int j = 0; j <= i; j++) {
cout << "*";
}
cout << endl;
}
There are fancier ways using std::string or stream formatting, but this is the quick fix to your existing code.
Another way, which only involves one inner loop, is to always write szam characters but decide within the loop whether those characters should be * or a whitespace, again using arithmetic:
int szam;
cin >> szam;
for (int i = 0; i < szam; i++) {
for (int j = 0; j < szam; j++) {
cout << (j < szam-i-1 ? ' ' : '*');
}
cout << endl;
}
With this version, your original "unmirrored" output can be obtained by using (j <= i ? '*' : ' ').
By the way, you shouldn't use endl in a loop — it's pointless. endl flushes the stream, whereas you just want a newline. The way to write a newline is cout << '\n'.
Also, check cin >> szam for success before proceeding.

There are really many many solutions for this problem. I show here an example using a std::string to create a string with the reuired number of stars.
I use also IO manipulators. Maybe that is what the teacher wants to see. So, we do right alignment and set a field width.
Please see:
#include <iostream>
#include <string>
#include <iomanip>
int main() {
// Inform the user what to do
std::cout << "\nEnter the width of the stair: ";
// Read the width of the stair and check, if the read operation was successful
if (unsigned int width{}; std::cin >> width) {
// Now print the full stair
for (unsigned int i = 0U; i < width; ++i) {
// Print stars
std::cout << std::right << std::setw(width) << std::string(i+1,'*') << "\n";
}
}
return 0;
}

for (int i = 1; i <= szam; i++) {
cout << string((szam-i),' ')<<string(i,'*') << endl;
}
If you want cout then just do this. The answers are numerous.

Related

How to end a user input array

So this is for a lab assignment and I already have it working, but one thing is bothering me. The assignment involves creating a 1-dimensional array and then manipulating it. I am supposed to allow a max of 100 inputs but the user does not have to use all 100. Right now, I am using a while statement to either break or allow another input to be entered. To break the statement, you have to enter a negative number (this is what I don't like and want to change). What other options are there to end the user input, once they are done entering their numbers? Is it possible to end the loop once you hit enter with nothing typed?
I have searched stackoverflow for the last 3 days and found some compelling stuff but could never get it to work.
Note, I get the void function is redundant here but that's besides the point (unless it actually affects my ability to achieve what I want).
Also, thanks in advance.
here is my code so far (my while statement is in the main)... be kind I'm a newbie to coding.
#include <iostream>
using namespace std;
void reverseElements(int array[], int size)
{
int tmp;
int j;
int i = size;
j = i - 1;
i = 0;
while (i < j)
{
tmp = array[i];
array[i] = array[j];
array[j] = tmp;
i++;
j--;
}
cout << "I will now reverse the elements of the array." << endl;
cout << endl;
for (i = 0; i < size; i++)
{
cout << array[i] << " " << endl;
}
}
int main()
{
const int NUM_ELEMENTS = 100;
int iArr[NUM_ELEMENTS];
int i;
int myInput;
cout << "Enter your numbers, then enter a negative number to finish" << endl;
cout << endl;
for (i = 0; i < NUM_ELEMENTS; i++) //loop to obtain input
{
cin >> myInput;
if (myInput < 0) //checks for negative number to end loop
{
break;
}
else //continues to allow input
{
iArr[i] = myInput;
}
}
cout << endl;
reverseElements(iArr, i);
return 0;
}
Probably the easiest solution: let your user choose how many numbers to write before actually writing them.
int readNumbersCount()
{
int const numbersMin = 1;
int const numbersMax = 100;
int numbersCount = -1;
while (numbersCount < numbersMin || numbersCount > numbersMax)
{
std::cout <<
"How many numbers are you going to enter? Choose from " <<
numbersMin << " to " << numbersMax << ":\n";
std::cin >> numbersCount;
}
return numbersCount;
}
int main()
{
int const numbersCount = readNumbersCount();
for (int i = 0; i < numbersCount; ++i)
{
// read the numbers etc.
}
return 0;
}
I wrote readNumbersCount() as a separate function to extract numbersMin and other "one-use" identifiers from main() and to make main()'s numbersCount const.
I have edited the main function a little bit.
Here the user is asked how many elements he wants to enter .
and doing the memory allocation dynamically so as to save space
int main()
{ int n=101;
while(n>100){
cout<<"How many numbers do you want to enter";
cin>>n;
}
int *ptr=new(nothrow)int[n];
for (int i=0;i<n;i++){
cout << "Enter your number" << endl;
cin>>ptr[i];
}
cout << endl;
reverseElements(ptr, n);
return 0;
}

my task is to print a string inside a frame for example a square

#include<iostream>
using namespace std;
int main()
{
int i=1,len;
char ch[26][26],ch2;
cout<<"enter string: "<<endl;
for(i=0;;i++)
{
cin>>ch[i];
len++;
if(getchar()=='\n')
break;
}
int n,j;
cout<<"enter size: "<<endl;
cin>>n;
int k;
for(i=0;i<=n;i++)
{
for(j=0;j<=n;j++)
{
if(i==0||i==n||j==0||j==n)
{
cout<<"*";
}
else
cout<<" ";
if(i==((n/2)-2)&&j==((n/2)-2))
{
for(k=0;k<len;k++)
{
cout<<ch[k]<<endl;
cout<<"*";
}
}
}
cout<<"\n";
}
}
this program is displaying string inside the square but the star pattern of squares is getting messed up espeacially the right most column
ANY HELP WOULD BE GREATLY APPRECIATED
Since you did not provide much details in your code, I started from the beginnig with a new code and this is what I came up with:
#include <iostream>
#include <vector>
Use a vector for your strings, with dynamic resizing (what if, in your code, I enter more than 26 words? Hint: segmentation fault!)
using std::vector;
using std::string;
using std::cout;
using std::cin;
using std::endl;
Using using namespace std; is best avoided. Just import what you really need.
int main() {
vector<string> strings;
You definitely want to use strings here, not char arrays.
cout << "Enter string: ";
Do not break line after an input prompt! (as a Linux user, I personnaly hate it)
for(;;) {
You do not need the variable i here, just run an infinite loop (try to rearrange that, once again if you can avoid infinite loops, a while(getchar() != '\n') is more self-explanatory.
string s;
cin >> s;
strings.push_back(s);
As pstrjds suggested in a comment, use getline() if you can.
if(getchar() == '\n')
break;
Like I said, try to reformulate with a while condition.
}
unsigned int n, i, j;
cout << "Enter size: ";
cin >> n;
// assuming strings.size() < n
unsigned int empty_lines_around_text((n - strings.size()) / 2);
Since you want to print your words centered inside your square, you have to display less than half a square of * (...) * lines: actually half a square minus half the number of strings to print.
// first horizontal row of stars
for(j = 0; j < n; ++j)
cout << '*';
cout << endl;
The upper side of the square.
for(i = 1; i < empty_lines_around_text; ++i) {
cout << '*';
for(j = 1; j < n - 1; ++j) {
cout << ' ';
}
cout << '*' << endl;
}
The first lines to print, those without string inside them.
//here we do the actual printing of the strings
for(i = 0; i < strings.size(); ++i) {
string s = strings[i];
// once again, assuming the size of each string is < n
unsigned int empty_chars_around_string((n - s.size()) / 2);
cout << '*';
for(j = 0; j < empty_chars_around_string; ++j)
cout << ' ';
cout << s;
for(j = empty_chars_around_string + s.size() + 1; j < n - 1; ++j)
cout << ' ';
cout << '*' << endl;
}
This is the problematic part. Like for the empty lines, we need a variable to contain how much spaces we have to print before the string so that it appears centered (variable empty_chars_around_string).
We print that much spaces, the string, and we complete the line with spaces before the line-ending *, and this for each string in the array.
for(i = empty_lines_around_text + strings.size() + 1; i < n; ++i) {
cout << '*';
for(j = 1; j < n - 1; ++j) {
cout << ' ';
}
cout << '*' << endl;
}
We complete the square with empty lines, after the strings have been printed.
// last horizontal line of '*' (we close the square)
for(j = 0; j < n; ++j)
cout << '*';
cout << endl;
...Aaand we close the square.
return 0;
}
Now, this code is not perfect, there is a bunch of refactoring and optimizing to do, but it maximizes the use of C++ features.
Here is a PasteBin with the whole code.
The output, when ran with the strings Hello friends and size 12:
************
* *
* *
* *
* *
* hello *
* friends *
* *
* *
* *
* *
************
The main problem lies at:
for(k=0;k<len;k++)
{
cout<<ch[k]<<endl;
cout<<"*";
}
Here when you come to place the input string, you also enter a new line and start with an asterisk (*). Not only you don't put the last asterisk on the input string's line, but you also don't update j there, it's still greater than 0 and when the code continues with for(j=0;j<=n;j++) j already has the leftover value from the newline + asterisk.
Try:
for( k = 0; k<len; k++ )
{
cout << ch[k];
j += strlen( ch[k] );
}
This way j will update to the last position of the input string.
PS: For common coding practise initialize len in the beginning to 0 as well.

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 <

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
}
}

C++ Program Debugging

I seem to be having some problems with my program. It compiles fine, but when I get to my first loop it asks me for a positive integer than it asks me again like its suppose too. Than it hops down a blank space and wont run any further until you enter another number which its not suppose to do. But than when you enter a number it goes back and asks me to enter an integer also like its suppose to the problem is, IT will do this infinite amount of times until I quit the program. Any suggestions as to why this is happening?
/* Search the entries of the n X n matrix mat in rowwise order for an entry to item */
#include <iostream>
using namespace std;
int main(void)
{
int n=10, item, row=3, col=3, mat[row][col];
bool found;
for (int row = 0; row < 3; row++)
for (int col = 0; col < 3; col++)
{
cout << "Enter Positive Integer : ";
cin >> row;
cout << " Enter Positive Integer : ";
cin >> mat[row][col];
}
cout << "Enter a positive integer you want to be searched: ";
cin >> item;
for(int i=0; i<row; ++i)
{
for(int j=0; j<col; ++j)
{
if(mat[row][col] == item)
found = true;
else
found = false;
}
}
if(found==true)
cout << "item found" ;
else
cout << "item found ";
return 0;
}
The line for (int cols = 0; cols < 5; col++) increments the variable col, not cols. Since cols is always 0, the loop will never terminate.
You've done the same in for (int rows = 0; rows < 5; row++). Infinite loops often occur due to typos in loop conditions ;)
I would also like to point out some logic errors during your search:
for(int i=0; i<row; ++i)
{
for(int j=0; j<col; ++j)
{
if(mat[row][col] == item)
found = true;
else
found = false;
}
}
When that loop ends, found will only be true if mat[row-1][col-1] == item (the very last element). Heck, row and col never change in the loop so you are repeatedly checking the exact same element every time! You should also expect even more funky program behavior if you don't get a grasp on your variable names. I strongly recommend adding debug statements to see how your variables are being modified throughout the program (aka: cout << "rows = " << rows << endl;, and cout << "i = " << i << endl;, etc). You're preparing a recipe for disaster when you reuse your variables.
Disclaimer: Reusing variables is not always a bad thing. However, it's best to avoid it until you have a stronger understanding of variables.
In your loop you are incrementing row and col not rows and cols.
It looks to me like you are using the same variable for the loop counter and the user input storage. That is doomed to not do what you want.
Do something like:
for (rowCounter = 0; rowCounter < 3; rowCounter++) {
for (colCounter = 0; colCounter < 3; colCounter++) {
cout << “Give me value for (“ << rowCounter << “,” << colCounter << “) :”;
cin >> mat[rowCounter][colCounter];
}
}
and then the rest of your code
It seems you had a couple of issues.
In the first for loop, you were incrementing the wrong variable (col instead of cols), you also went from 0 to 4 in a 3x3 matrix
you asked the user for 2 numbers then you asked the user to put in a number in the matrix, but its only a 3x3 matrix, the user could easy go out of bounds. I think what you were trying to do was populate the matrix with users number. So i made that change.
In the second for loop, you set found =true, but the loop will keep going, meaning the last number it searched, if it was false, then found = false, also changed it to mat[i][j] instead of mat[row][col], so it doesn't check the same one every time.
both found = true and found = false would return "item found", i think you left off the "not" in the second hard coded string.
I added a pause so you can read the output at the end.
I fixed them and I think this code should do what you want it to now.
#include <iostream>
using namespace std;
int main(void)
{
int n=10, item, row = 3, col = 3;
int mat[3][3];
bool found = false;
int j,k;
for (int rows = 0; rows < 3; rows++)
for (int cols = 0; cols < 3; cols++)
{
cout << "Enter row Integer: ";
cin >>j;
cout << "Enter col Integer: ";
cin >> k;
cout << "Enter Positive Integer : ";
cin >> mat[j][k];
}
cout << "Enter a poistive integer you want to be searched: ";
cin >> item;
int flag = 0;
for(int i=0; i<row; ++i)
{
for(int j=0; j<col; ++j)
{
if(mat[i][j] == item)
{
flag = flag + 1;
}
}
}
if(flag > 0)
found = true;
if(found==true)
cout << "item found" ;
else
{
cout << "item not found ";
}
system("PAUSE");
return 0;
}