I wanna print two diamonds side by side, but my code prints 1 diamond.
I spent lots of time on it and really do not know what else to do.
Any help would be appreciated.
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
int i,j,n, middle, spaceCount, starCount;
cin >> n;
middle = (n - 1) / 2;
for ( i = 0; i < n; i++)
{
spaceCount = abs(middle - i);
starCount = n - 2 * abs(middle - i);
for ( j = 0; j < spaceCount; j++)
cout << " ";
for (j = 0; j < starCount; j++)
cout << "*";
for (j = 0; j < spaceCount; j++)
cout << " ";
cout << endl;
}
}
input = odd numbers
desired output =
* *
*** ***
**********
*** ***
* *
You forgot to print you second diamond shape. Each iteration, you should print first a few spaces, then the stars, then the double of the spaces (to finish the first diamond and set spaces for the second diamond) and then you should draw you stars for your second diamond.
This is an example of code that prints two diamonds:
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
int i,j,n, middle, spaceCount, starCount;
cin >> n;
middle = (n - 1) / 2;
for ( i = 0; i < n; i++)
{
spaceCount = abs(middle - i);
starCount = n - 2 * abs(middle - i);
// print a row of the first diamonds
// spaces at the beginning
for ( j = 0; j < spaceCount; j++)
cout << " ";
// the stars itself
for (j = 0; j < starCount; j++)
cout << "*";
// finish the rectangle of the first diamond
for (j = 0; j < spaceCount; j++)
cout << " ";
// print a row of the second diamond
// spaces at the beginning
for (j = 0; j < spaceCount; j++)
cout << " ";
// the stars itself
for (j = 0; j < starCount; j++)
cout << "*";
// spaces at the end are not necessarily required for the last diamond
cout << endl;
}
}
It would be even better to create a function to print one diamond (row) and call this function two times (this prevents duplicate code).
Related
I have a line of code that when inputted 3, the result will print out a series of dashes and asterisks to form a diamond:
Expected Input:
3
Expected Output:
--*--
-***-
*****
-***-
--*--
what i have so far is the triangle but I can' seem to get rid of the middle line to make it a full diamond shape. Also "-" is not printing on the right side of the bottom half
this is the code I have made
int n;
cin >> n;
for (int left_stars = 0; left_stars < n; left_stars++) {
for (int column = 0; column < 2 * n - 1; column++) {
int first_star = n - 1 - left_stars;
int last_star = n - 1 + left_stars;
if (column < first_star || column > last_star) {
cout << "-";
} else {
cout << "*";
}
}
cout << endl;
}
for(int i = n; i >= 1; --i) {
for(int space = 0; space < n-i; ++space) {
cout << "-";
}
for(int j = i; j <= 2*i-1; ++j) {
cout << "*";
}
for(int j = 0; j < i-1; ++j) {
cout << "*";
}
cout << endl;
}
return 0;
For removing the double full star line use following code line
for (int i = n-1; i >= 1; --i) {
instead of
for(int i = n; i >= 1; --i) {
(side note: maybe you want to check as suggested by yaodav if you could not write the second part like the first part).
very basic Q as I just started with coding but I stuck at some point and have 0 ideas what to do.
I need to write code to get diamond shape made from dots and X letters, size based on a value (n) provided by the user, (3 ≤ n ≤ 80).
for example:
As I mentioned - I have almost 0 experience so all I could get is is this shape for n=6
height is ok, same as widht but unfortunately, the amount of X's and placement isn't correct :/
my code:
int h;
cerr << "Provide size of diamond: ";
cin >> h;
for (int i = 1; i <= h; i++)
{
for (int k = 1 ; k <= h-i ; k++)
{
cout << ".";
}
for (int j = 1; j <= i ; j++)
{
cout << "X";
}
cout << endl;
Thank you all good people who will help mi with this one :)
I help to draw points. I hope you, looking on my change, are able to update your code further to achive the required picture.
for (int i = 1; i <= h; i++)
{
for (int k = 1 ; k <= (h-i) / 2 ; k++)
{
cout << ".";
}
for (int j = 1; j <= i ; j++)
{
cout << "X";
}
for (int k = 1 ; k <= (h-i) / 2 ; k++)
{
cout << ".";
}
cout << endl;
}
In this kind of problems you can divide the problems in different parts. Such as for n=6 the image can be divided in 4 mirror images:
..X
.XX
XXX
then,
X..
XX.
XXX
and upside down mirror of them.
You said that you can draw the first one. I think if you give some more time you will be able to print the full image too.
But, if you have problems, here's the code for that
for (int i = 1; i <= h; i++) {
if((h-i)%2) continue;
for (int j = 1 ; j <= (h-i) / 2 ; j++) {
cout << ".";
}
for (int j = 1; j <= i ; j++) {
cout << "X";
}
for (int j = 1 ; j <= (h-i) / 2 ; j++) {
cout << ".";
}
cout << endl;
}
for (int i = (h/2)*2; i > 0; i--) {
if((h-i)%2) continue;
for (int j = 1 ; j <= (h-i) / 2 ; j++) {
cout << ".";
}
for (int j = 1; j <= i ; j++) {
cout << "X";
}
for (int j = 1 ; j <= (h-i) / 2 ; j++) {
cout << ".";
}
cout << endl;
}
Since this is tagged as a c++ question let's use std::string and three loops.
#include <iostream>
#include <string>
void print_diamond(int n)
{
int np = n / 2, nm = (n - 1) / 2;
int npl = np, nml = nm;
std::string str(n, '.');
for (int i = 0; i < nm; i++)
{
str[npl++] = 'X'; str[nml--] = 'X';
std::cout << str << std::endl;
}
for (int i = nm; i <= np; i++)
{
str[npl] = 'X'; str[nml] = 'X';
std::cout << str << std::endl;
}
for (int i = np; i < n - 1; i++)
{
str[npl--] = '.'; str[nml++] = '.';
std::cout << str << std::endl;
}
std::cout << std::endl;
}
Print all diamond for a shinier world...
int main()
{
for (int n = 3; n < 81; n++)
{
print_diamond(n);
}
}
I need help, I created a short little program a while ago where it would print a simple pyramid with "*" like this:
*
***
*****
but I decided to challenge myself and see if I could create a simple diamond shape like this:
*
***
*****
***
*
Here is my code so far.
I should also add that the value you input, for example 5, determines how big the diamond is.
#include <iostream>
#include <sstream>
using namespace std;
int main() {
int value = 0;
cout << "Please enter in a value: ";
cin >> value;
cout << endl;
for (int i = 0; i < value; i++) {
//print spaces v v v
for (int x = 0; x < (value - i - 1); x++) {
cout << " ";
}
//print * v v v
for (int y = 0; y < (2 * i + 1); y++) {
cout << "*";
}
cout << endl;
}
for (int i = 0; i < value; i++) {
int number = 0;
number+= 2;
//print spaces v v v
for (int x = 0; x < (value - value + i + 1); x++) {
cout << " ";
}
//print * v v v
for (int y = 0; y < (/*ATTENTION: What do I do here? Plz help*/); y++) {
cout << "*";
}
cout << endl;
}
return 0;
}
What I've been trying to do is figure out what to put inside the parenthesis where it says (//ATTENTION). I've been working for at least an hour trying to do random things, and one time it worked when I input 4, but not for 5, and it's just been very hard. This is key to building the diamond, try putting in just value and compile to see what happens. I need it to be symmetrical.
I need to know what to put inside the parenthesis please. I'm sorry this is very long but the help would be appreciated thanks.
I also apologize if my code is messy and hard to read.
int number = 0; and number+= 2;
value - value inside for (int x = 0; x < (value - value + i + 1); x++) {
are not required.
Inside the parenthesis, you can use
2*(value-i-1)-1
However, I would suggest you to first analyze the problem and then try to solve it instead of trying random things. For instance, let's consider the cases of even and odd inputs i.e., 2 and 3.
Even Case (2)
*
***
***
*
The Analysis
Row Index Number of Spaces Number of Stars
0 1 1
1 0 3
2 0 3
3 1 1
For row index < value
Number of Spaces = value - row index - 1
Number of Stars = 2 * row index + 1
For row index >=value
The number of spaces and stars are simply reversed. In the odd cases, the situation is similar too with a small exception.
Odd Case (3)
*
***
*****
***
*
The Analysis
Row Index Number of Spaces Number of Stars
0 2 1
1 1 3
2 0 5
3 1 3
4 2 1
The small exception is that while reversing, we have to ignore the row index = value.
Now, if we put the above analysis in code we get the solution
//Define the Print Function
void PrintDiamond(int rowIndex, int value)
{
//print spaces v v v
for (int x = 0; x < value - rowIndex -1; x++) {
cout << " ";
}
//print * v v v
for (int y = 0; y < 2 * rowIndex + 1; y++) {
cout << "*";
}
cout << endl;
}
And then inside main
//Row index < value
for (int i = 0; i < value; i++) {
PrintDiamond(i,value);
}
//For row index >= value reversing the above case
//value-(value%2)-1 subtracts 1 for even and 2 for odd cases
//ignore the row index = value in odd cases
for (int i = value-(value%2)-1; i >=0; i--) {
PrintDiamond(i,value);
}
#include <iostream>
#include <sstream>
using namespace std;
int main() {
int value = 0;
cout << "Please enter in a value: ";
cin >> value;
cout << endl;
for (int i = 0; i < value; i++) {
//print spaces v v v
for (int x = 0; x < (value - i - 1); x++) {
cout << " ";
}
//print * v v v
for (int y = 0; y < (2 * i + 1); y++) {
cout << "*";
}
cout << endl;
}
for (int i = 0; i < value-1; i++) {
// int number = 0;
// number+= 2;
// //print spaces v v v
for (int x = 0; x < i+1; x++) {
cout << " ";
}
//print * v v v
for (int y = 0; y < (2*(value-1-i)-1); y++) {
cout << "*";
}
cout << endl;
}
return 0;
}
I hope that you will get this .Also in the second for loop you were iterating it one extra time by iterating the loop upto value. But since the pyramid is symmetric so the no of rows in the pyramid will be 2*value-1.So I in the second loop i should vary upto value -1.
This code should resolve the problem:
#include <sstream>
using namespace std;
void printSpaces(int howMany) {
for(int i = 0; i < howMany; i++) cout << " ";
}
void figure(int size) {
bool oddSize = size % 2 == 1;
int center = size / 2;
int spaces = size / 2;
// If figure is of an odd size adjust center
if (oddSize) {
center++;
} else { // Else if figure is of even size adjust spaces
spaces--;
}
for (int i = 1; i <= center; i++) {
printSpaces(spaces);
for(int j = 0; j < 1 + (i - 1) * 2; j++) cout << "*";
cout << endl;
spaces--;
}
spaces = oddSize ? 1 : 0; // If the figure's size is odd number adjust spaces to 1
center -= oddSize ? 1 : 0; // Adjust center if it's an odd size figure
for(int i = center; i >= 1; i--) {
printSpaces(spaces);
for(int j = 0; j < 1 + (i - 1) * 2; j++)
cout << "*";
cout << endl;
spaces++;
}
}
int main() {
int value = 0;
while(value < 3) {
cout << "Please enter in a value (>= 3): ";
cin >> value;
cout << endl;
}
figure(value);
return 0;
}
I am currently working on a task which says the following:
Input a two-dimensional array A (m,n) [m < 10, n < 20]. In the n + 1 column calculate the sum of the rows, and in the m + 1 row the product of the columns. Print out the resulting matrix.
According to my understanding of this task, at the end of each column must be the sum of according rows (so on the right hand side), and the product of the column (at the end/bottom?).
This task is so confusing I do not know where to start. I found some code that covers the idea but does not include the product and it does not display these values as the task asks me to:
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a[3][3];
int i, j, s = 0, sum = 0;
cout << "Enter 9 elements of 3*3 Matrix \n";
for (i = 0; i < 3; i++)
for (j = 0; j < 3; j++)
cin >> a[i][j];
cout << "Matrix Entered By you is \n";
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
cout << a[i][j] << " ";
cout << endl;
}
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
s = s + a[i][j];
cout << "sum of" << i + 1 << " Row is" << s;
s = 0;
cout << endl;
}
cout << endl;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
s = s + a[j][i];
cout << "sum of" << i + 1 << " Column is" << s;
s = 0;
cout << endl;
}
cout << endl;
for (i = 0; i < 3; i++)
sum = sum + a[i][i];
cout << "Sum of Diagnols Elements is \n" << sum;
getch();
}
We beginners should help each other.
Here you are
#include <iostream>
#include <iomanip>
int main()
{
const size_t M = 10;
const size_t N = 20;
int a[M][N] = {};
std::cout << "Enter number of rows: (less than " << M << "): ";
size_t m;
std::cin >> m;
if (!(m < M) || (m == 0)) m = M - 1;
std::cout << "Enter number of columns: (less than " << N << "): ";
size_t n;
std::cin >> n;
if (!(n < N) || (n == 0)) n = N - 1;
std::cout << std::endl;
for (size_t i = 0; i < m; i++)
{
std::cout << "Enter " << n
<< " numbers for the row " << i << ": ";
for (size_t j = 0; j < n; j++) std::cin >> a[i][j];
}
for (size_t j = 0; j < n; j++) a[m][j] = 1;
for (size_t i = 0; i < m; i++)
{
for (size_t j = 0; j < n; j++)
{
a[i][n] += a[i][j];
a[m][j] *= a[i][j];
}
}
std::cout << std::endl;
for (size_t i = 0; i < m + 1; i++)
{
for (size_t j = 0; j < n + 1; j++)
{
std::cout << std::setw(3) << a[i][j] << ' ';
}
std::cout << '\n';
}
std::cout << std::endl;
}
The program output might look like
Enter number of rows: (less than 10): 3
Enter number of columns: (less than 20): 3
Enter 3 numbers for the row 0: 1 2 3
Enter 3 numbers for the row 1: 4 5 6
Enter 3 numbers for the row 2: 7 8 9
1 2 3 6
4 5 6 15
7 8 9 24
28 80 162 0
So you have to declare an array with 10 rows and 20 columns. The user should enter the dimensions of the array that are correspondingly less than 10 and 20. One row and one column are reserved for sums and products.
It is desirable that the array would be initially initialized by zeroes.
int a[M][N] = {};
In this case you need not to set the last column with zeroes as you have to do with last row initializing it with ones.
That is all.:)
Start with the declaration: make sure that your program works with m×n matrix, not simply a 3×3 matrix. Since m and n have limits of 10 and 20, and because you must add an extra row and a column to the result, the declaration should be
int a[11][21];
You also need to declare m and n, have end-user enter them, and validate them to be within their acceptable ranges:
int m, n;
cin >> m >> n;
... // Do the validation
Now you can rewrite your loops in terms of m and n, rather than using 3 throughout your code.
With these declarations in place, you can total the numbers in place, i.e. for each row r you would write
for (int i = 0 ; i != n ; i++) {
a[r][n+1] += a[r][i];
}
Similarly, you would compute the product (don't forget to start it with the initial value of 1, not 0).
At the end you would print an (m+1)×(n+1) matrix to complete the task.
Solution : use this kind of functions for your array after making it global.
void Adder(int row, int colum)
{
for (int i = 0; i < row - 1; i++)
{
int temp = 0;
for (int j = 0; j < colum - 1; j++)
{
temp += a[i][j]; // added all other than last one
}
a[i][j] = temp; // assigned to last one in row
}
}
void Mul(int row, int colum)
{
for (int i = 0; i < colum- 1; i++)
{
int temp = 1;
for (int j = 0; j < row - 1; j++)
{
temp *= a[j][i]; // multiplied all element other than last one
}
a[j][i] = temp; // assigned to last one in column
}
}
So I have an assignment for my C++ class. Basically we have to create a 3x3 multidimensional array, calculate the sum of rows, sum of columns, sum of diagonal values and sum of anti-diagonal values, I usually just input 1 2 3 4 5 6 7 8 9 as values as a starting point.
Now, I'm not trying to be rude but my teacher is not very good, we basically spend 2 hours on a single problem without her doing much explaining. Other than that I started with C++ Primer and Programming: Principles and Practice Using C++ so I believe I'll be able to learn a lot on my own.
Anyhow my questions are probably quite stupid, but if anyone feels like helping, here they are:
My /**/ commented for loop for anti-diagonal value gives me a wrong sum. I'm assuming it has something to do with the nature of for-loops or I just type it out wrong, but I didn't figure it out yet.
2.The teacher's solution for calculating the anti-diagonal values is the following:
for (i = 0; i < row_num; ++i)
for (j = 0; j < col_num; ++j)
if (i + j == row_num - 1)
anti-diagonal += A[i][j];
How is it different from my approach? I believe mine is simpler and works better.
3.In line:
int sumRows[row_num] = { 0 };
Why do {} have to be used? Our teacher didn't bother with explaining that. I tried without {} but I got an error.
Here is the full code for my version:
#include "../../std_lib_facilities.h"
#include <iostream>
using namespace std;
#define row_num 3 //no. of rows
#define col_num 3 //no. of columns
int main()
{
int i = 0;
int j = 0;
int diagonal = 0;
int antidiagonal = 0;
int sumRows[row_num] = { 0 };
int sumCol[col_num] = { 0 };
int A[row_num][col_num];
//Input to matrix
for(i=0; i<row_num; i++)
for (j = 0; j < col_num; j++)
{
cout << "A[" << i << "]" << "[" << j << "]: ";
cin >> A[i][j];
sumRows[i] += A[i][j];
sumCol[j] += A[i][j];
}
cout << endl;
//Print out the matrix
for (i = 0; i < row_num; i++)
{
for (j = 0; j < col_num; j++)
cout << A[i][j] << '\t';
cout << endl;
}
//prints sum of rows
for (i = 0; i < row_num; i++)
cout << "Sum of row " << i + 1 << " "<< sumRows[i] << endl;
//prints sum of columns
for (j = 0; j < row_num; j++)
cout << "Sum of column " << j + 1 << " " << sumCol[j] << endl;
//Sum of diagonal values
for (i = 0; i < row_num; i++)
diagonal += A[i][i];
//Sum of antidiagonal values
for (i = 0, j = 2; i < row_num, j >= 0; i++, j--)
antidiagonal += A[i][j];
/*for(i=0; i<row_num; i++)
for (j = 2; j >= 0; j--)
{
antidiagonal += A[i][j];
}
*/
cout << "\nSum of diagonal values: " << diagonal << endl;
cout << "Sum of antdiagonal values: " << antidiagonal << endl;
return 0;
}
1) Your commented out loop sums all values, not just those along the antidiagonal.
2) It is different from your approach in that it will iterate over every value in the matrix, but then it will only add to the total if it detects it is in one of the appropriate cells. Your solution only iterates over the appropriate cells and doesn't have to evaluate any ifs, so it will be more efficient. However, you need to change your loop condition to i < row_num && j >= 0. Using a comma here will discard the result of one of the checks.
3) int sumRows[row_num] = { 0 }; initializes the whole sumRows array with 0's.
1) This
for(i=0; i<row_num; i++)
for (j = 2; j >= 0; j--)
{
antidiagonal += A[i][j];
}
is wrong, because for i=0 you iterate through all j values, ie
i=0 , j=2,1,0 then i=1
2) Your teachers loop is easier to read and correct. Yours has a wrong break condition:
for (i = 0, j = 2; i < row_num, j >= 0; i++, j--)
^------------------------ WRONG
Read about the comma operator to understand what is actually going on here. You just didnt realize the problem, because the two conditions are by chance equivalent.
3) You dont have to use it, it is just a new and fancy way to initialize the array.