This question already has an answer here:
Printing a “triangle” of asterisks, in c++
(1 answer)
Closed 4 years ago.
I am trying to print out the shape of a triangle but I am kinda lost...
this is what I have so far:
#include <iostream>
using namespace std;
int main()
{
int i, k, n;
cout << "Please enter number of rows you want to see: \n";
cin >> n;
for (k = 1; k <= n; k++)
{
for (i = 1; i <= k; i++)
cout << '*';
cout << endl;
}
getchar();
getchar();
return 0;
}
This code works fine for a right angled triangle -
*
**
***
But I guess you want a triangle like this -
*
***
*****
Try this -
#include <iostream>
using namespace std;
int main()
{
int i, j, k, n;
cout << "Please enter number of rows you want to see: \n";
cin >> n;
for (k = 1; k <= n; k++)
{
for(j = 1; j <= n-k; j++)
cout << ' ';
for (i = 1; i <= 2*k-1; i++)
cout << '*';
cout << endl;
}
return 0;
}
I think the code is pretty straightforward to understand. The first inner for loop is to print the spaces and the second inner for loop is to print the *
This does print the shape of a triangle. For example, when you put in 5, the program outputs
*
**
***
****
*****
If your computer isn't printing this output, it's not a problem with your code.
Related
I want a pattern in which for n=4 in 1st row it has 4 stars and in 2nd row I has 1 space & 3 stars and in 3rd row, it has 2 spaces and 2 stars and so on.
****
***
**
*
The code, I tried to solve this.
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
cout << endl;
int i = 1;
while (i <= n)
{
//Printing Spaces
int space = i - 1;
while (space)
{
cout << " ";
space++;
}
//Printing Stars
int j = 1;
while (j <= n)
{
cout << "*";
j++;
}
cout << endl;
i++;
}
return 0;
}
In your while (space) loop you aren't comparing space to anything, so it assumes that the expression is always true.
Here's a simplified way to do it:
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
cout << endl;
int i = 1;
while (i <= n)
{
// print i-1 spaces
for (int j = i-1; j >= 1; j--)
{
cout << " ";
}
// print n-i+1 stars
for (int j = n; j >= i; j--){
cout << "*";
}
cout << endl;
i++;
}
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
cout << endl;
int i = 1;
while (i <= n)
{
int space = i - 1;
while (space>=1) // change 1.1
{
cout << " ";
space--; // change 1.2
}
int j = i; // change2
while (j <= n)
{
cout << "*";
j++;
}
cout << endl;
i++;
}
return 0;
}
I made only 2 changes in your code so it can work.
1st one
while (space>=1)
what you are doing is you are trying to add space in output so you add space variable in while() loop but that's not going to work because you have to decide first how many spaces you have to print according to that you have to put condition in while() loop. To achieve this space--; added .
For ex. line 4 i=4; space want 3, so space=3; while(space>=1); space--; so while loop runs 3 time and print 3 gaps/spaces.
2nd one
int j = i;
while (j <= n)
if you put j=1; then your gaps print properly but all stars print 4 times as loop runs 4 times always. Due to this condition for i=1; But if you make j=i;
loop runs 4 times for 1st line, 3 times for 2nd line,.....
#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.
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
}
}
I am trying to make a code for one of the problems on an online coding platform. I have already made the code, but cannot get the input in the desired format. I need to take an input which has three integers (say n1, n2 and m). The question says that the input can be numbers separated by white spaces. I tried looking for help and even found a way, but it isn't working.
Here is my code:
#include <string>
#include <ctype.h>
#include <iostream>
#include <conio.h>
#include <stdlib.h>
using namespace std;
int main()
{
int t;
cout << "Enter the number of test cases" << endl;
cin >> t;
do
{
string rawInput;
int isNum, n1, n2, m, t, i, j;
int arr[3];
arr[0] = 0;
arr[1] = 0;
arr[2] = 0;
cout << "Enter a number, or numbers separated by a space, between 1 and 1000." << endl;
while (getline(cin, rawInput))
{
cout << "Rawinput" << rawInput.length();
for (i = 0; i < rawInput.length(); ++i)
{
cout << rawInput[i];
}
int j = 0, k = 0;
for (int j; j < rawInput.length(); ++j)
{
isNum = isdigit(rawInput[j]);
if (isNum)
{
arr[k] = arr[k] * 10 + atoi(rawInput[j]);
}
else
k = k++;
}
cout << "I am Array" << endl;
for (int l = 0; l < 3; l++)
cout << arr[l] << endl;
}
if (arr[0] >= arr[2] && arr[1] >= arr[2])
{
for (int i = 1; i <= arr[2]; i++)
{
if (arr[0] >= i && arr[1] >= i)
{
arr[0] = arr[0] - i;
arr[1] = arr[1] - i;
}
}
}
cout << arr[1] + arr[0];
t--;
} while (t > 0);
}
Specifically the function atoi doesn't seem to work. I tried using stoi, but even that isn't working.
If you are simply trying to collect a series of integers separated by spaces as user input..ie 1 2 3 4 5, you don't have to user the getline method.
You can redo the while loop for a condition like this:
int input;
while (cin >> input)
{
<<HANDLE INPUT>>
}
This is drastically reduce the line parsing you are trying to do and will capture the next inputted integer on that line as long as there is one to take. The loop iteration will go like this with the same series above...
Loop # Input Taken
1 1
2 2
3 3
... ...
This way there is no parsing necessary as it will handle ONE integer input per iteration.
I am trying to write a program to count each number the program has encountered. by putting M as an input for the number of the array elements and Max is for the maximum amount of number like you shouldn't exceed this number when writing an input in the M[i]. for some reason the program works just fine when I enter a small input like
Data input:
10 3
1 2 3 2 3 1 1 1 1 3
Answer:
5 2 3
But when I put a big input like 364 for array elements and 15 for example for max. the output doesn't work as expected and I can't find a reason for that!
#include "stdafx.h"
#include <iostream>
#include<fstream>
#include<string>
#include <stdio.h>
#include<conio.h>
using namespace std;
int ArrayValue;
int Max;
int M[1000];
int checker[1000];
int element_cntr = 0;
int cntr = 0;
int n = 0;
void main()
{
cout << "Enter the lenght of the Elements, followed by the maximum number: " << endl;
cin >> ArrayValue>> Max;
for (int i = 0; i < ArrayValue; i++)
{
cin >> M[i];
checker[i]= M[i] ;
element_cntr++;
if (M[i] > Max)
{
cout << "the element number " << element_cntr << " is bigger than " << Max << endl;
}
}
for (int i = 0; i < Max; i++)
{
cntr = 0;
for (int j = 0; j < ArrayValue; j++)
{
if (M[n] == checker[j])
{
cntr+=1;
}
}
if (cntr != 0)
{
cout << cntr << " ";
}
n++;
}
}
You have general algorithm problem and several code issues which make code hardly maintainable, non-readable and confusing. That's why you don't understand why it is not working.
Let's review it step by step.
The actual reason of incorrect output is that you only iterate through the first Max items of array when you need to iterate through the first Max integers. For example, let we have the input:
7 3
1 1 1 1 1 2 3
While the correct answer is: 5 1 1, your program will output 5 5 5, because in output loop it will iterate through the first three items and make output for them:
for (int i = 0; i < Max; i++)
for (int j = 0; j < ArrayValue; j++)
if (M[n] == checker[j]) // M[0] is 1, M[1] is 1 and M[2] is 1
It will output answers for first three items of initial array. In your example, it worked fine because the first three items were 1 2 3.
In order to make it work, you need to change your condition to
if (n == checker[j]) // oh, why do you need variable "n"? you have an "i" loop!
{
cntr += 1;
}
It will work, but both your code and algorithm are absolutely incorrect...
Not that proper solution
You have an unnecessary variable element_cntr - loop variable i will provide the same values. You are duplicating it's value.
Also, in your output loop you create a variable n while you have a loop variable i which does the same. You can safely remove variable n and replace if (M[n] == checker[j]) to if (M[i] == checker[j]).
Moreover, your checker array is a full copy if variable M. Why do you like to duplicate all the values? :)
Your code should look, at least, like this:
using namespace std;
int ArrayValue;
int Max;
int M[1000];
int cntr = 0;
int main()
{
cout << "Enter the lenght of the Elements, followed by the maximum number: " << endl;
cin >> ArrayValue >> Max;
for (int i = 0; i < ArrayValue; i++)
{
cin >> M[i];
if (M[i] > Max)
{
cout << "the element number " << i << " is bigger than " << Max << endl;
}
}
for (int i = 0; i < Max; i++)
{
cntr = 0;
for (int j = 0; j < ArrayValue; j++)
{
if (i == M[j])
{
cntr ++;
}
}
if (cntr != 0)
{
cout << cntr << " ";
}
}
return 0;
}
Proper solution
Why do you need a nested loop at all? You take O(n*m) operations to count the occurences of items. It can be easily counted with O(n) operations.
Just count them while reading:
using namespace std;
int arraySize;
int maxValue;
int counts[1000];
int main()
{
cout << "Enter the lenght of the Elements, followed by the maximum number: " << endl;
cin >> arraySize >> maxValue;
int lastReadValue;
for (int i = 0; i < arraySize; i++)
{
cin >> lastReadValue;
if (lastReadValue > maxValue)
cout << "Number " << i << " is bigger than maxValue! Skipping it..." << endl;
else
counts[lastReadValue]++; // read and increase the occurence count
}
for (int i = 0; i <= maxValue; i++)
{
if (counts[i] > 0)
cout << i << " occurences: " << counts[i] << endl; // output existent numbers
}
return 0;
}