i've had a problem with this code, it skips to 3 asterisks, and my desired program follows the asterisks in order. such as 1 to 2 to 3 asterisks and so on. I want the program to only accept numbers and not special characters.
*
**
***
****
*****
****
***
**
*
Example of desired output ^
Code:
#include <iostream>
using namespace std;
int main() {
cout << "Enter a number: ";
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n - i; j++) {
cout << " ";
}
for (int j = 1; j <= 2 * i - 1; j++) {
cout << "*";
}
cout << endl;
}
for (int i = n - 1; i >= 1; i--) {
for (int j = 1; j <= n - i; j++) {
cout << " ";
}
for (int j = 1; j <= 2 * i - 1; j++) {
cout << "*";
}
cout << endl;
}
return 0;
}
I input 5 for example, and the asterisks don't follow, it just skips to 3, for example, 1, 3, and so on.
Let me give you some explanation how to find a solution for this problem.
Let us break a big problem into smaller ones.
If we look at the number of asterisks, so, just at the characters, not at the identation or leading spaces, then we see for the input 5:
Row Asterics Number of asterics
0 0
1 * 1
2 ** 2
3 *** 3
4 **** 4
5 ***** 5
6 **** 4
7 *** 3
8 ** 2
9 * 1
10 0
So, we need a function, that will transform the row number to the number of asterics. And, we see a pattern, that looks like a pyramid or triangle.
And this will lead us to the triangular function. Please read here about it. And in this kind of functions the "absolute value" plays a role. In C++ we can use std::abs for this.
Additionally, we can see, that the number of leading spaces to create a diamond is simply the given width minus the number of asterics, divided by 2.
With this know how we can now do the following simple calculation:
Number of stars leading blanks
Row width-abs(row-width) abs(row-width)/2
0 0 5/2 = 2
1 1 4/2 = 2
2 2 3/2 = 1
3 3 2/2 = 1
4 4 1/2 = 0
5 5 0/2 = 0
6 4 1/2 = 0
7 3 2/2 = 0
8 2 3/2 = 1
9 1 4/2 = 2
10 0 5/2 = 2
Additionally we can see the the number of rows is 2 times the width.
With all that, we can come up with a simple program that uses only one for loop.
#include <iostream>
#include <cmath>
#include <algorithm>
#include <string>
int main() {
// Get the max width of the pattern and perform a short input validation
int maxWidth{};
if ((std::cin >> maxWidth) and (maxWidth > 0)) {
// The number of rows for the pattern is dependent on the width. It is a simple relation
const int numberOfRows = 2 * maxWidth;
// Show all rows
for (int row = 1; row < numberOfRows; ++row) {
// Use triangle formular to create star pattern
const std::string starPattern(maxWidth - std::abs(row - maxWidth), '*');
// Create leading spaces
const std::string leadingSpaces(std::abs(row - maxWidth)/2, ' ');
// Show output
std::cout << leadingSpaces << starPattern << '\n';
}
}
else std::cout << "\n*** Error: Invalid input\n\n";
}
Please note. For creating the strings, we use the its constructor number 2. Here you can specify the std::strings length and the filling character.
And if you do not want to use strings, then you need to add again 2 for loops.
Please see:
#include <iostream>
#include <cmath>
int main() {
// Get the max width of the pattern and perform a short input validation
int maxWidth{};
if ((std::cin >> maxWidth) and (maxWidth > 0)) {
// The number of rows for the pattern is dependent on the width. It is a simple relation
const int numberOfRows = 2 * maxWidth;
// Show all rows
for (int row = 1; row < numberOfRows; ++row) {
// Calculate number of characters using the trinagular formular idea
const int numberOfStars = maxWidth - std::abs(row - maxWidth);
const int numberOfSpaces = std::abs(row - maxWidth) / 2;
// print leading spaces
for (int i = 0; i < numberOfSpaces; ++i)
std::cout << ' ';
// print stars
for (int i = 0; i < numberOfStars; ++i)
std::cout << '*';
// Create new line
std::cout << '\n';
}
}
else std::cout << "\n*** Error: Invalid input\n\n";
}
And, if you have even no std::abs the you can create such a function by yourself.
Then the code will be
#include <iostream>
int absValue(int v) {
if (v < 0) v = -v;
return v;
}
int main() {
// Get the max width of the pattern and perform a short input validation
int maxWidth{};
if ((std::cin >> maxWidth) and (maxWidth > 0)) {
// The number of rows for the pattern is dependent on the width. It is a simple relation
const int numberOfRows = 2 * maxWidth;
// Show all rows
for (int row = 1; row < numberOfRows; ++row) {
// Calculate number of characters using the trinagular formular idea
const int numberOfStars = maxWidth - absValue(row - maxWidth);
const int numberOfSpaces = absValue(row - maxWidth) / 2;
// print leading spaces
for (int i = 0; i < numberOfSpaces; ++i)
std::cout << ' ';
// print stars
for (int i = 0; i < numberOfStars; ++i)
std::cout << '*';
// Create new line
std::cout << '\n';
}
}
else std::cout << "\n*** Error: Invalid input\n\n";
}
The output is the same as you have specified it. Please look for the last example with width 5:
And here with width 20:
Related
ive got the below code to print a pattern (attached below). However i'd like to just use one loop
#include<iostream>
using namespace std;
int main(){
int n;
cin>>n;
for(int i=1;i<=n;i++){
for(int j=1;j<=i;j++){
cout<<"*";
}
for(int j=1;j<=n-i;j++){
if(j%2!=0){
cout<<"_";
}else{
cout<<".";
}
}
cout<<endl;
}
for(int i=1;i<n;i++){
for(int j=1;j<=n-i;j++){
cout<<"*";
}
for(int j=1;j<=i;j++){
if(j%2==0){
cout<<".";
}else{
cout<<"_";
}
}
cout<<endl;
}
}
when n = 5, heres the output.
*_._.
**_._
***_.
****_
*****
****_
***_.
**_._
*_._.
how do i just make this into one single loop
Try this and see how it does what you want to understand the step you did not find on your own:
#include<iostream>
using namespace std;
int main() {
int n;
cin >> n;
for (int i = 1; i <= n*2-1; i++) {
if (i <= n)
{
for (int j = 1; j <= i; j++) {
cout << "*";
}
for (int j = 1; j <= n - i; j++) {
if (j % 2 != 0) {
cout << "_";
}
else {
cout << ".";
}
}
cout << endl;
}
else
{
for (int j = 1; j <= n*2 - i; j++) {
cout << "*";
}
for (int j = 1; j <= i-n; j++) {
if (j % 2 == 0) {
cout << ".";
}
else {
cout << "_";
}
}
cout << endl;
}
}
}
I'd like to just use one loop.
I'll take it literally and show a starting point for a possible solution.
// Let's start by figuring out some dimensions.
int n;
std::cin >> n;
int height = 2 * n - 1;
int area = n * height;
// Now we'll print the "rectangle", one piece at a time.
for (int i = 0; i < area; ++i)
{ // ^^^^^^^^
// Extract the coordinates of the char to be printed.
int x = i % n;
int y = i / n;
// Assign a symbol, based on such coordinates.
if ( x <= y and x <= height - y - 1 )
{ // ^^^^^^ ^^^^^^^^^^^^^^^^^^^ Those are the diagonals.
std::cout << '*'; // This prints correctly the triangle on the left...
}
else
{
std::cout << '_'; // <--- But of course, something else should done here.
}
// End of row.
if ( x == n - 1 )
std::cout << '\n';
}
If you look at the pattern, then you can see a sort of "triangles". And this already gives a hint for the solution. Use a triangle function.
Please read about it here.
Then you will notice that always the "aboslute"-function, in C++ std::abs, is involved.
But first of all, it is easily visible that the number rows to print is always the width of a triangle * 2.
And the number of charcters in the pattern, can be calculated by applying the triangle function. Example for width 5:
Number of stars number of dashdot
Row width-abs(row-width) abs(row-width)
1 1 4
2 2 3
3 3 2
4 4 1
5 5 0
6 4 1
7 3 2
8 2 3
9 1 4
And this can be implemented easily now.
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std::string_literals;
int main() {
// Get the max width of the pattern and perform a short input validation
int maxWidth{};
if ((std::cin >> maxWidth) and (maxWidth > 0)) {
// The number of rows for the pattern is dependent on the width. It is a simple relation
const int numberOfRows = 2 * maxWidth;
// Show all rows
for (int row = 1; row < numberOfRows; ++row) {
// Use triangle formular to create star pattern
std::string starPattern(maxWidth - std::abs(row - maxWidth), '*');
// Create dashDot pattern
std::string ddp(std::abs(row - maxWidth), '\0');
std::generate(ddp.begin(), ddp.end(), [i = 0]() mutable { return i++ % 2 ? '.' : '_'; });
// Show output
std::cout << (starPattern+ddp) << '\n';
}
}
else std::cout << "\n*** Error: Invalid input\n\n";
}
Of course you can also create the whole pattern wit std::generate.
Maybe it is too complex for now.
And less understandable.
See:
#include <iostream>
#include <string>
#include <cmath>
#include <algorithm>
#include <vector>
int main() {
// Get the max width of the pattern and perform a short input validation
if (int width{}; (std::cin >> width) and (width > 0)) {
std::vector<std::string> row(2 * width - 1);
std::for_each(row.begin(), row.end(), [&, r = 1](std::string& s) mutable {
s = std::string(width - std::abs(r - width), '*');
std::string ddp(std::abs(r++ - width),'\0');
std::generate(ddp.begin(), ddp.end(), [&, i = 0]() mutable{ return i++ % 2 ? '.' : '_'; });
s += ddp; std::cout << s << '\n'; });
}
else std::cout << "\n*** Error: Invalid input\n\n";
}
Hello and thank you for coming here.
I have to do a program that will draw a number of square choosed by the user with incremental letter.
For example, if the user choose 4 square, it will return :
DDDDDDD
DCCCCCD
DCBBBCD
DCBABCD
DCBBBCD
DCCCCCD
DDDDDDD
At the time being, my code look like this ;
#include <iostream>
using namespace std;
int main()
{
int size;
int nbsquareletter;
cout << " How many square ?" << endl;
cin >> nbsquareletter;
size = nbsquareletter * 2 - 1;
char squareletter = 'a';
for (int row = 1; row <= size; ++row)
{
for (int col = 0; col <= size; ++col)
{
if (row < col) {
cout << (char)(squareletter + row - 1) << " ";
}
else if (row > col)
{
cout << (char)(squareletter + col) << " ";
}
/*
cout << col << " ";
cout << row << " ";
*/
}
cout << endl;
}
}
If you have any ideas to help me, don't hesitate, I'm struggling. it's been 3.5 hours. Thanks you for reading and have a good day !
Try to keep things simple. If you start write code before you have a clear idea of how to solve it you will end up with convoluted code. It will have bugs and fixing them will make the code even less simple.
Some simple considerartions:
The letter at position (i,j) is determined by the "distance" from the center. The distance is max(abs(i - i_0), abs(j - j_0).
The center is at (i,j) = (size-1,size-1) when we start to count at upper left corner (0,0).
The letters can be picked from an array std::string letters = "ABCDEFG...".
i and j are in the range [0,2*size-1)
Just writing this (and nothing more) down in code results in this:
#include <iostream>
#include <string>
void print_square(int size){
std::string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int i_0 = size-1;
int j_0 = size-1;
for (int i=0;i< 2*size-1;++i){
for (int j=0;j< 2*size-1;++j) {
int index = std::max(std::abs(i-i_0),std::abs(j-j_0));
std::cout << letters[index];
}
std::cout << "\n";
}
}
int main() {
print_square(4);
}
Which produces output
DDDDDDD
DCCCCCD
DCBBBCD
DCBABCD
DCBBBCD
DCCCCCD
DDDDDDD
Your code cannot print the right output, because when row == col there is no output, and it misses the diagonal. I didnt look further than that.
Instead of fixing bugs in your code I decided to suggest you my own solution. Maybe some other answers will be related to bugs in your code.
On piece of paper I figured out 4 different formulas for 4 parts of a drawn picture, formulas computing what letter to take inside English alphabet. Afterwards I take this letter from array with alphabet.
Try it online!
#include <iostream>
int main() {
int n = 0;
std::cin >> n;
char const letters[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (int i = 0; i < 2 * n - 1; ++i) {
for (int j = 0; j < 2 * n - 1; ++j)
std::cout << letters[
i <= j && i + j < 2 * n - 1 ? n - i - 1 :
i <= j && i + j >= 2 * n - 1 ? j - n + 1 :
i > j && i + j < 2 * n - 1 ? n - j - 1 :
i > j && i + j >= 2 * n - 1 ? i - n + 1 : 25
];
std::cout << std::endl;
}
}
Input:
7
Output:
GGGGGGGGGGGGG
GFFFFFFFFFFFG
GFEEEEEEEEEFG
GFEDDDDDDDEFG
GFEDCCCCCDEFG
GFEDCBBBCDEFG
GFEDCBABCDEFG
GFEDCBBBCDEFG
GFEDCCCCCDEFG
GFEDDDDDDDEFG
GFEEEEEEEEEFG
GFFFFFFFFFFFG
GGGGGGGGGGGGG
Let's define some functions, to make the recurrence relation obvious.
std::vector<std::string> WrapInLetter(char letter, std::vector<std::string> lines)
{
for (auto & line : lines)
{
line.insert(line.begin(), letter);
line.insert(line.end(), letter);
}
std::size_t size = (lines.size() * 2) + 1;
std::string edge(size, letter); // A string formed of size copies of letter
lines.insert(lines.begin(), edge);
lines.insert(lines.end(), edge);
return lines;
}
std::vector<std::string> SquareLetter(char letter)
{
if (letter == 'A') return { "A" };
return WrapInLetter(letter, SquareLetter(letter - 1));
}
Now main just has to call that function and loop over the result.
int main()
{
std::cout << "How many square ?" << std::endl;
int size;
std::cin >> size;
for (auto line : SquareLetter('A' + size - 1))
{
std::cout << line << std::endl;
}
}
I'm sorry if this is a silly question.
I have written the following piece of code for coin change problem.
#include <iostream>
using namespace std;
int coinChange(int coins[], int n, int amount)
{
int combinations[amount + 1];
combinations[0] = 1;
int start;
for(int i = 0; i < n; i++)
{
start = coins[i];
int coin = coins[i];
for(int j = start; j < amount + 1; j++)
{
if(j >= coin)
{
combinations[j] += combinations[j - coin];
}
}
for(int j = 0; j < amount + 1; j++)
cout << combinations[j] << " ";
cout << endl;
}
return combinations[amount];
}
int main(int argc, char const *argv[])
{
int coins[] = {1, 2, 5};
int n = sizeof(coins)/sizeof(coins[0]);
int amount = 12;
// cout << "Total combinations: ";
cout << coinChange(coins, n, amount) << endl;
return 0;
}
The code works fine and provides me the correct output as shown below.
1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 2 2 3 3 4 4 5 5 6 6 7
1 1 2 2 3 4 5 6 7 8 10 11 13
13
However, If I uncomment the line cout << "Total combinations: "; just above the function calling in the main function, the program gives me bizzare outputs.
Total combinations: 1 32768 32768 32768 44137 44137 44137 44137 196418491 196418492 -790461916 -790429149 619621115
1 32768 32769 65536 76906 109673 121043 153810 196539534 196572302 -593922382 -593856847 25698733
1 32768 32769 65536 76906 109674 153811 186579 196605070 196649208 -593812708 -593703036 25885312
25885312
Is executing cout before function calling causing this random outputs? Or is this a problem for my version of compiler?
What about initialize (to zero?) combinations ?
Something like
int combinations[amount + 1] {};
Otherwise the initial values of combinations[i] are undefined indeterminate, so are is undefined the final values behavior of the program (correction from Shafik Yaghmour; thanks!)
Do this in your coinChange function.
int combinations[amount + 1]{};
combinations[0] = 1;
int start;
for(int i = 0; i < n; i++)
{
start = coins[i];
int coin = coins[i];
for(int j = start; j < amount + 1; j++)
{
if(j >= coin)
{
combinations[j] += combinations[j - coin];
}
}
for(int j = 0; j < amount + 1; j++)
cout << combinations[j] << " ";
cout << endl;
}
Now uncomment the line and run. The basic problem is when you create the combinations array, you have to initialize the elements to 0. If you don't, they may be all 0 by a lucky coincidence, but you can't guarantee that.
EDIT : Using empty initializer list to initilize array with zeros as max66 suggested.
I was solving a simple problem on spoj called Ambiguous Permutations(http://www.spoj.com/problems/PERMUT2/), it worked fine when I tested for small inputs, but on submission it shows runtime error - segmentation fault. I'm not able to figure it out (though I've wasted a lot of time, and gained frustration only). Please help.
#include <iostream>
#include <stdlib.h>
#include <string.h>
char arr1[200000];//stores original string.
char arr2[200000];//stores inverse permutation.
long int n;
using namespace std;
int main()
{
while (1)
{
cin >> n;
if (n == 0)
{
exit(0);
}
getchar();
gets(arr1);
//creating inverse permutation.
for (long int i = 0; i < 2 * n - 1; i++)
{
if (i % 2 == 1)
{
arr2[i] = ' ';
}
else
{
arr2[2 * (arr1[i] - '0') - 2] = i / 2 + '1';
}
}
arr2[2 * n - 1] = '\0';
//comparing string with it's inverse permutation.
if (strcmp(arr1, arr2) == 0)
{
cout << endl << "ambiguous";
}
else
{
cout << endl << "not ambiguous";
}
}
return 0;
}
The problem is that you are using a char array to represent integers, and your code assumes that each number is represented by one char (note for example checking i % 2 == 1 to determine whether number or space).
Hence, any number bigger than 9 will cause correctness / memory problems.
If you'll use integer arrays it will be a lot easier.
You'll stop worrying about the space character ' ', won't need to decrement '0' char from the cells, and won't need your loops to run till 2 * n - 1.
I think it is much clearer this way:
#include <iostream>
using namespace std;
const int MAX_SIZE = 1000;
int arr1[MAX_SIZE];
int arr2[MAX_SIZE];
int size = 0;
bool areArrsEqual()
{
for (int i = 0; i < size; ++i)
{
if (arr1[i] != arr2[i])
{
return false;
}
}
return true;
}
int main()
{
cin >> size;
while (size > 0 && size <= MAX_SIZE)
{
for (int i = 0; i < size; ++i)
{
cin >> arr1[i];
}
// creating inverse permutation.
for (int i = 0; i < size; i++)
{
// if (arr[i] - 1 >= size) ==> illegal input.
arr2[arr1[i] - 1] = i + 1;
}
// comparing permutation with it's inverse permutation.
if (areArrsEqual())
{
cout << "ambiguous" << endl;
}
else
{
cout << "not ambiguous" << endl;
}
cin >> size;
}
return 0;
}
Output:
4
1 4 3 2
ambiguous
5
2 3 4 5 1
not ambiguous
1
1
ambiguous
13
1 2 3 4 5 6 7 8 9 10 11 12 13
ambiguous
0
I have to print out a triangle-star formed shape as such where the user specifies the intial number of asterisks--be it 10, 25, or 30.
***** (5)
*** (3)
* (1)
OR
********** (10)
********
******
****
**
*
I have written the code with three loops--two nested in one--using C++ Someone else claims that it can be done only using two loops but I can't seem to figure it out. In my head, its like asking to draw a triangle out of only 2 lines; it simply cannot work. I would appreciate it if someone could confirm if it can be done with only two loops and if so provide a hint or explanation.
Theoretical computer science says that every problem can be solved in one loop.
This doesn't mean that it's always easy, but in your case, it fortunately is!
How about this program, http://ideone.com/nTnTC8:
#include <iostream>
using namespace std;
int main(int argc, char* argv[]) {
int startNum = 0;
cin >> startNum;
if (startNum <= 0) return 1;
cout << startNum << endl;
int numCols = startNum;
int numRows = (startNum + 1) / 2;
if (numCols % 2 == 0) {
++numRows;
}
int numFields = numCols * numRows;
for (int currentField = 0; currentField < numFields; ++currentField) {
int currentRow = currentField / numCols;
int currentCol = currentField % numCols;
if (currentCol < currentRow) cout << "-";
else if (currentCol > (numCols - currentRow - 1))
if (currentRow == numRows - 1 && currentCol == numCols / 2)
cout << "^";
else cout << "_";
else cout << "*";
if (currentCol == numCols - 1) cout << endl;
}
return 0;
}
To use 2 for loops, you will have one loop for the lines and another nested loop for the characters.
An "if" statement can be used to determine whether to print a '*' or space.
Another alternative is to use functions that create strings of repetitive characters.
Edit 1:
This may come in handy, centering formula for text:
starting_position = center_position - (character_count / 2);
One loop is sufficient, to enumerate all lines. To print N spaces on line N, use the std::string(N, ' ') constructor.
Strictly speaking, this code does the trick using 2 loops :
int n, s, z;
cout << "Enter the width \n";
cin >> n;
// for each row
for (int i = 0; i < n/2+1; i++) {
z = i; // set number of spaces to print
s = (n-i*2) + (i == n/2 ? (1-n%2) : 0); // set number of stars to print
// still something to print
while (z+s > 0) {
if ( z ) {
cout << " ";
z--;
} else if ( s ) {
cout << "*";
s--;
}
}
cout << endl;
}