Hello guys I just want to ask how can I create a triangle using c++?
Actually I have my code but I don't have an idea how to center the first asterisk in the triangle. My triangle is left align. How can I make it a pyramid?
Here's my code below.
#include<iostream>
using namespace std;
int main(){
int x,y;
char star = '*';
char space = ' p ';
int temp;
for(x=1; x <= 23; x++){
if((x%2) != 0){
for(y=1; y <= x ; y++){
cout << star;
}
cout << endl;
}
}
return 0;
}
For a triangle och height Y, then first print Y-1 spaces, followed by an asterisk and a newline. Then for the next line print Y-2 spaces, followed by three asterisks (two more than previously printed) and a newline. For the third line print Y-3 spaces followed by five asterisks (again two more than previous line) and a newline. Continue until you have printed your whole triangle.
Something like the following
int asterisks = 1;
for (int y = HEIGHT; y > 0; --y, asterisks += 2)
{
for (int s = y - 1; s >= 0; --s)
std::cout << ' ';
for (int a = 0; a < asterisks; ++a)
std::cout << '*';
std::cout << '\n';
}
To calculate the number of spaces needed to center each row use this algorithm:
numSpaces = (23 - x) / 2;
and then a for loop to apply the spaces numSpaces times.
Here is the complete code:
#include<iostream>
using namespace std;
int main(){
int x,y;
char star = '*';
char space = ' p ';
int temp;
int numSpaces = 0;
for(x=1; x <= 23; x++){
if((x%2) != 0){
numSpaces = (23 - x) / 2; // Calculate number of spaces to add
for(int i = 0; i < numSpaces; i++) // Apply the spaces
{
cout << " ";
}
for(y=1; y <= x ; y++){
cout << star;
}
cout << endl;
}
}
return 0;
}
And the output:
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
*********************
***********************
One way to do
this is to nest two inner loops, one to print spaces and one to print *(s), inside an outer
loop that steps down the screen from line to line.
#include <iostream>
using namespace std;
int main(){
int row = 5;
for(int i=0; i<row; i++){
for(int j=row; j>i; j--){
cout << " ";
}
for(int k=0; k<2*i+1; k++){
cout << "*";
}
cout << endl;
}
return 0;
}
Output:
*
***
*****
*******
*********
This code is in C#, but you can convert it in c++.
class Program
{
static void Main()
{
int n = 5; // Number of lines to print.
for(int i = 1; i<= n; i++){
//loop for print space in the order (4,3,2,1,0) i.e n-i;
for(int j= 1; j<= n-i; j++){
Console.Write(" ");
}
//loop for print * in the order (1,3,5,7,9..) i.e 2i-1;
for(int k= 1; k<= 2*i-1; k++){
Console.Write("*");
}
Console.WriteLine(); // Next Line.
}
}
}
Here's another solution that doesn't use division or if statements
#include <iostream.h>
int main() {
int height = 17, rowLength, i, j, k;
char symbol = '^';
// print a pyramid with a default height of 17
rowLength = 1;
for (i = height; i > 0; i--) { // print a newline
cout << endl;
for (j = 1; j <= i; j++) // print leading spaces
cout << " ";
for (k = 0; k < rowLength; k++) // print the symbol
cout << symbol;
rowLength = rowLength + 2; // for each row increase the number of symbols to print
}
cout << "\n\n ";
return 0;
}
Star pyramid using for loop only:-
#include <iostream>
#include <conio.h>
#include <iomanip>
using namespace std;
int main()
{
int n;
cout << "enter the number of rows of pyramid you want : ";
cin >> n;
"\n";
for (int i = 0; i <= n; ++i) {
cout << "\n";
for (int j = 0; j <= n - i; ++j) {
cout << " ";
}
for (int k = 1; k <= i; k++) {
cout << setw(3) << "*";
}
}
return 0;
}
I did that using two loops
here is my code
#include <iostream>
#include <string>
using namespace std;
int main() {
int rows, star, spaces;
int number_of_stars = 5;
int number_of_rows = number_of_stars;
string str1 = "*";
for (rows=1; rows <= number_of_rows; rows++) {
for (spaces=1; spaces <= number_of_stars; spaces++) {
if (spaces==number_of_stars)
{
cout<<str1;
str1+="**";
}
else
cout<<(" ");
}
cout<<("\n");
number_of_stars = number_of_stars - 1;
}
return 0;
}
and the result is
*
***
*****
*******
*********
Url of code on Online compiler
and you can solve it using only one loop, its simple and easy
#include <iostream>
#include <string>
using namespace std;
int main()
{
int numberOfLines=4;
string spaces=string( numberOfLines , ' ' );//this is 4 spaces
string stars="*";
while(spaces!="")
{
cout<<spaces<<stars<<endl;
spaces = spaces.substr(0, spaces.size()-1);
stars+="**";
}
}
Url of code on Online compiler
#include<iostream>
using namespace std;
int for1(int &row);//function declaration
int rows;//global variable
int main()
{
cout<<"enter the total number of rows : ";
cin>>rows;
for1(rows);//function calling
cout<<"just apply a space at the end of the asteric and volla ";
}
int for1(int &row)//function definition
{
for(int x=1;x<=row;x++)//for loop for the lines
{
for(int y=row;y>=x;y--) //for loop for spaces (dynamic loop)
{
cout<<" ";
}
for(int k=1;k<=x*2-x;k++)//for loop for asteric
{
cout<<"* ";/*apply a space and you can turn a reverse right angle triangle into a pyramid */
}
cout<<endl;
}
}
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";
}
I want to generate a random string with letters a,b,c,d then let the user guess it.
My output should be which positions the user guessed correctly and how many letters the user guessed correctly but put them in the wrong position.
Current attempt:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;
int main()
{
char lettres[4] =
{
'a',
'b',
'c',
'd'
};
char rString[4];
int i = 0;
srand(time(0));
while (i < 4)
{
int temp = rand() % 4;
rString[i] = lettres[temp];
i++;
}
int u = 0;
char t[4];
while (u < 10)
{
cout << "Enter your guess:\n ";
cin >> t;
for (int z = 0; z < 4; z++)
{
cout << rString[z] << ", "; //printing random string
}
cout << "\n";
int k;
int compteur = 0;
int t2[4];
int compteur2 = 0;
for (k = 0; k < 4; k++)
{
if (rString[k] == t[k]) //rString is my random string
{
t2[compteur2] = k;
compteur2++;
}
}
for (int y = 0; y < 4; y++)
for (int j = 0; j < 4; j++)
{
if (t[y] == rString[j] && y != j) //checking correct letters at wrong positions
{
compteur++;
t[y] = 'z'; //I put this line to avoid counting a letter twice
}
}
if (compteur2 == 4)
{
cout << "bravo\n";
u = 10;
} else
{
cout << "Positions with correct letters:\n ";
if (compteur2 == 0)
{
cout << "None";
cout << " ";
} else
for (int z = 0; z < compteur2; z++)
c out << t2[z] << ", ";
cout << " \n";
cout << "You have a total of " << compteur << " correct letters in wrong positions\n";
}
u++;
}
return 1;
}
Sample output:
Enter your guess:
abcd
b, a, b, a, //note this is my random string I made it print
Positions with correct letters:
None
You have a total of 1 correct letters in wrong positions
for example here I have 2 correct letters in the wrong position and I am getting 1 as an output
To clarify more about why I put t[y]='z'; if for example the random string was "accd" and my input was "cxyz" I would get that I have 2 correct letters at wrong positions, so I did that in attempt to fix it.
Any help on how to do this?
You should implement like this
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;
int main() {
srand(time(0));
char lettres[4] = {'a','b','c','d'};
char rString[4];
int i = 0;
//making random string
while (i < 4) {
int temp = rand() % 4;
rString[i] = lettres[temp];
i++;
}
int u = 0;
char t[4];
while (u < 10) {
cout << "Enter your guess:\n ";
cin >> t;
//printing random string
for (int z = 0; z < 4; z++) {
cout << rString[z] << ", ";
}
cout << "\n";
int correctPositions = 0;
cout << "Correct Position Are:\n";
for (int z = 0; z < 4; z++) {
if (rString[z] == t[z]) {
cout << (z + 1) << ", ";
correctPositions++;
}
}
if (correctPositions == 4) {
cout << "\nBingo!" << "\nThat's Right!";
return 0;
}
if (correctPositions == 0) {
cout << "None";
}
cout << "\n";
//finding no of correct letters in wrong position:
int correctLetters = 0;
for (int i = 0; i < 4; i++) {
char c = lettres[i];
int randomCount = 0;
int guessCount = 0;
int letterInCorrectPos = 0;
for (int z = 0; z < 4; z++) {
if (rString[z] == c) {
randomCount++;
}
if (t[z] == c) {
guessCount++;
}
if (rString[z] == t[z] && t[z] == c)
letterInCorrectPos++;
}
correctLetters += min(guessCount, randomCount) - letterInCorrectPos;
}
cout << "No. of correct letters but in wrong position :" << correctLetters;
cout << "\n\n";
u++;
}
return 0;
}
Explaining Logic
1. Finding No. Of Correct Positions:
This is done by iterating with z = 0 -> z=4 over the rString and t if rString[z] is t[z] (the char at z are matching) then we just print the position!
2. Finding No. Of Correct Letters In Wrong Position
This part was little tricky to implement but here is the method I followed.
We have lettres[] array which is containing all the letters, right? We will now individual loop over each letter in the array and count the no. of occurrence in the rString and t, and store the respective counts in a randomCount and guessCount respectively.
Ex. let rString = "bdcc" and t = "abcd" so we have the following data:
'a': randomCount:0 guessCount:1 letterInCorrectPos: 0
'b': randomCount:1 guessCount:1 letterInCorrectPos: 0
'c': randomCount:2 guessCount:1 letterInCorrectPos: 1
'd': randomCount:1 guessCount:1 letterInCorrectPos: 0
This is the first part in the above loop you can see we have another variable letterInCorrectPos, this variable stores the no. of instances in the string where, the letter is at the same position in both the strings.
Figuring these three values we can calculate the no. of correct letter:
correctLetters = min(guessCount, randomCount)
the smaller value of guessCount or randomCount is chosen because we don't want repeated counting. (We can't have more correct letters than there are instances of that letter in another class).
Now by simple logic: correct letters in wrong place is (correct letters) - (correct letters in the correct place ).Hence,
correctLetters = min(guessCount, randomCount) - letterInCorrectPos;
Since we are iterating in a loop and we want to add correctLetters of each letter, we use this statement at the end of loop:
correctLetters += min(guessCount, randomCount) - letterInCorrectPos;
Hope this will explain the working.
I have coded this program and it works fine. I get the result I want but because we are using an old system to submit it, my code is rejected because it saying that the 3 last lines generate a blank of my code. Can someone please tell me where is the problem and how I can fix it? Thank you!
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int i, row_nr;
cin >> row_nr;
if(row_nr > 1 && row_nr <= 30)
for(i = 1; i <= row_nr; i++)
{
for(int j = 0; j < row_nr; j++)
{
cout << i + j * (row_nr);
{
cout << " ";
}
}
cout << endl;
}
return 0;
}
You're outputting a space after every value, so there is going to be a space at the end of each line. You should add a check so that you don't output a space after the last value of each line. It seems like you might have intended to do this, but forgot to write the if statement.
#include <iostream>
//#include <iomanip> why?
using namespace std;
int main()
{
int row_nr;
cin >> row_nr;
if(row_nr > 1 && row_nr <= 30)
for(int i = 1; i <= row_nr; i++) //declare iterator variable in for loop statement
{
for(int j = 0; j < row_nr; j++)
{
cout << i + j * (row_nr);
if(j < row_nr - 1) //you forgot this line
{
cout << " ";
}
}
cout << '\n'; //endl flushes the buffer, unnecessary here
}
return 0;
}
The original question was to create a triangle out of hashes like this:
########
######
####
##
I decided to split the triangle in half and create half of each shape. Right now I have the code to create this shape:
####
###
##
#
code:
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main () {
for (int row = 1; row <= 4; row++) {
for (int hashNum = 1; hashNum <= 5 - row; hashNum++) {
cout << "#";
}
cout << endl;
}
}
However, I cannot figure out how to create the other half of the shape. Does anyone have any ideas?
Here is a very step-by-step way to do it. Note there are more elegant ways to do this, namely recursion comes to mind.
#include <iostream>
void DrawTriangle(unsigned int rows)
{
// Loop over the rows
for(unsigned int spaces = 0; spaces < rows; ++spaces)
{
// Add the leading spaces
for(unsigned int i = 0; i < spaces; ++i)
{
std::cout << ' ';
}
// Add the hash characters
for(unsigned int j = 0; j < (rows - spaces)*2; ++j)
{
std::cout << '#';
}
// Add the trailing spaces
for(unsigned int i = 0; i < spaces; ++i)
{
std::cout << ' ';
}
// Add a newline to complete the row
std::cout << std::endl;
}
}
int main() {
DrawTriangle(4);
return 0;
}
Output
########
######
####
##
Sure: treat the blank area as a triangle of spaces, and double the width of your current triangle.
First of all I would consider the parameters of your problem. You are trying to draw a triangle of n rows of height with ascii chars. Considering that you take off one char on each side of the row on the next line, the minimum width of the base of your triangle is 2*(n-1)+1. For example, if you have n=3:
#####
###
#
Doing it this way your triangle shape will be better, with only one '#' at the bottom. After that the program is more straightforward. you can make something like this:
#include <iostream>
using namespace std;
void DrawInvTri(unsigned int nrows)
{
unsigned int ncols= (nrows-1)*2+1;
for (int i=0; i<nrows; i++)
{
// Write spaces before tri
for (unsigned int j=0; j<i; j++)
cout << " ";
// Write actual tri chars
for (unsigned int k=i; k<(ncols - i); k++)
cout << "#";
// Next line
cout << endl;
}
}
int main()
{
DrawInvTri(5);
DrawInvTri(3);
DrawInvTri(4);
return(0);
}
i want to write a program to draw the shape of X letter using asterisk(*)
#include "stdafx.h"
#include <iostream>
using namespace std;
int main(int argc, char* argv[]){
int i, j;
for(i = 1; i <= 9; i++){
for(j = 1; j <= 12; j++){
if(i == j){
cout << "***";
}else{
cout << " ";
}
}
cout<< endl;
}
return 0;
}
i am very new to programming
i only made (\) how can I make the whole X
***------***
-***----***-
--***--***--
---******---
--***--***--
-***----***-
***------***
that's what i did uptill now
include "stdafx.h"
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
int i, d, a=1,b=12,c;
for(i = 1; i <= 6; i++)
{
for (d=1; d<i;d++) {cout <<" ";}
cout<<"***";
for (c=a+1; c<b;c++) {cout <<" ";}
{cout<<"***";}
for(b=12-i;b<i;b++)
{cout<<"***";}
cout<<endl;
a++;
}
return 0;
}
i divided the top of the (\//) to three parts
[space][][space][]
I have written the following function/method in java. You can convert it to c++;
public static void printX(int x) {
char[] chars = new char[x];
for (int i = 0; i < x; i++) {
chars[i] = '*';
chars[x - 1 - i] = '*';
for (int j = 0; j < x; j++) {
if (j == i || j == (x - 1 - i)) {
continue;
}
chars[j] = ' ';
}
System.out.println(new String(chars));
}
}
If you call the above function/method as printX(5); The output will by 5x5 sized and containing X character.
* *
* *
*
* *
* *
**** ****
*** ***
** **
* *
** **
*** ***
**** ****
Firstly, pardon my very uneven X. For you as a beginner I would give out an algo for you to ponder upon rather than spoon feeding a code.
The interpreter does not know how to come back to a line which has already been printer.
Therefore, you would have to draw both sides of the X in one iteration of the loop.
After that you decrease you star count (star--) and draw line # 2.
Repeat till the mid way mark when your stars are 0.
When your code sees that the stars are 0, then start with the same loop but this time star++ in each iteration.
This is repeated till the starting count of the star i.e 4 in my case.
If any problems you can post your code on the site :)
You shall dynamically evaluate the spacing areas in each row. Draw manually desired shape on piece of paper and try to create function, which takes as an argument the row number and returns amount of spaces required in the specific row. For example:
* *
* *
*
* *
* *
The amount of spaces in each row equals:
0 [*] 3 [*]
1 [*] 1 [*]
2 [*]
1 [*] 1 [*]
0 [*] 3 [*]
Note, that inside each row you'll need two loops: first for the initial and middle spaces.
The solution I wrote 2 decades ago (when I was still learning):
Make an line-column array, e.g. char screen[80][25];
Clear it by setting all entries to ' '
"Draw a point" at x,y by setting screen[x][y]='*';
When done, render the whole screen[80][25] by calling cout 2080 times. (2000 times for the characters and and 80 times for endl)
In your case, you know how to draw a \. You can easily adapt this. But with my method, you can then draw a / in the same screen array. And when you're done, you have an overlapping / and \ at the last step: X
I used this method since we had to draw a circle and that's really a lot harder. And yes, nowadays I'd probably use std::vector<std::string> screen but back then screens were really 80x25 :)
#include "stdafx.h"
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
int i, d, a=1,b=12,c ,e=1;
for(i = 1; i <= 6; i++)
{
for (d=1; d<i;d++) {cout <<" ";}
cout<<"***";
for (c=a+1; c<b;c++) {cout <<" ";}
{cout<<"***";}
for(b=12-i;b<i;b++)
{cout<<"***";}
cout<<endl;
a++;
}
for( i = 1; i <= 3; i++)
{
for ( d=6; d>i;d--) {cout <<" ";}
cout<<"***";
for (c=0; c<e-1;c++) {cout <<" ";}
{cout<<"***";}
cout<<endl;
e++;
}
return 0;
}
int n=11,i=0,k=0,j=0;
for(i=0;i<n;i++)
{
if(i<(n/2))
{
cout<<endl;
for(j=0;j<i;j++)
{
cout<<" ";
}
cout<<"*";
for(k=n/2;k>i;k--)
{
cout<<" ";
}
cout<<"*";
}
else
{
cout<<endl;
for(k=n-1;k>i;k--)
{
cout<<" ";
}
cout<<"*";
for(j=n/2;j<i;j++)
{
cout<<" ";
}
cout<<"*";
}
}
#include<iostream>
using namespace std;
int main()
{
int i, j;
for(i = 1;i<= 5;i++)
{
for(j = 1;j<= 5;j++)
{
if((i == j)||(j==(5+1)-i))
{
cout << "*";
}
else{
cout << " ";
}
}
cout<< endl;
}
system("pause");
}
#include "stdafx.h"
#include <iostream>
using namespace std;;
int _tmain(int argc, _TCHAR* argv[])
{
int i,k,j;
for (i=1;i<8;i++)
{
for (int k=0;k<i;k++)
{
cout<<" ";
}
cout<<"*";
for (int k=8;k>i;k--)
{
cout<<" ";
}
cout<<"*";
cout<<endl;
}
for (i=1;i<8;i++)
{
for (int k=8;k>i;k--)
{
cout<<" ";
}
cout<<"*";
for (int k=0;k<i;k++)
{
cout<<" ";
}
cout<<" *";
cout<<endl;
}
system("Pause");
return 0;
}