for(int width=1; width<=5; width++) {
if(width <= 1) {
for(int width=1; width<=5; width++) {
cout<<" "<<width<<" ";
}
} else if(width<5) {
cout<< endl;
for(int width2=5; width2<=9; width2++) {
if(width2==5 || width2==9)
cout<<" "<<width2<<" ";
else
cout<< " ";
}
} else {
cout<< endl;
for(int width3=13; width3>=9; width3--) {
cout<<" "<<width3<<" ";
}
}
}
this code which I have posted above draws this shape
1 2 3 4 5
5 9
5 9
5 9
13 12 11 10 9
but I actually want my code to print it like this, I have tried a lot changing things but all in vain. so, I'm looking forward to you guys.
1 2 3 4 5
16 6
15 7
14 8
13 12 11 10 9
If you print something on the console, going back in lines and carriage returns will be very messy.
The trick is to seperate the problem in 3 stages:
stage1: print the top line, simple enough
stage2: print the largest number wrapping around, then print some empty space and finish with the number at the end, make sure to increment and decrement the numbers accordingly.
stage3: print the last line.
Here is the code for the algorithm I just described:
#include <iostream>
using namespace std;
int main()
{
const int width=6;
const int height=6;
int numberInFront=(height-1)*2 + (width-1)*2;
int numberAtTheEnd= width;
for(int i=1; i<width; ++i) cout<<i<<"\t"; //print top line
cout<<endl;
for(int i=0; i<height-1; ++i)
{
cout<<numberInFront<<"\t";
for(int j=0; j<width-3; j++) cout<<"\t"; //print inner space
cout<<numberAtTheEnd<<endl;
numberInFront--;
numberAtTheEnd++;
}
//print last line:
int counter = numberInFront;
while(counter!=numberAtTheEnd-1)
{
cout<<counter<<"\t";
counter--;
}
return 0;
}
It helps to avoid magic numbers in your code using #defines or const variables. This makes it more readable and more extensible. For example if you wanted to make a square that was 20x20, your code would require a complete rewrite!
Start from this working solution to implement this principle into your coding.
#include <iostream>
using namespace std;
#define SIDE 4
int main(){
int perimeter = SIDE * 4;
for(int width=0; width<=SIDE; width++)
{
if(width < 1) {
for(int width=0; width <= SIDE; width++) {
cout<<" "<<width + 1<<" ";
}
cout<< endl;
}
else if(width < SIDE)
{
cout<<" "<<perimeter - width + 1 << "\t\t" << (SIDE + width) + 1;
cout<< endl;
}
else
{
for(int width3 = perimeter - SIDE; width3 >= perimeter - 2 * SIDE; width3--) {
cout<<" "<<width3 + 1<<" ";
}
cout<< endl;
}
}
return 0;
}
Here is solution
int width =6;
int total = (width-1)*4;
for(int row=1; row <=width; row++)
{
if(row == 1 )
{
for(int pr=1; pr<=width; pr++)
{
cout<<" "<<pr<<" ";
}
cout<<"\n";
}
else if( row == width)
{
for(int pr=1; pr<=width; pr++)
{
cout<<" "<<(total-row-pr+3)<<" ";
}
}
else
{
for(int pr=1; pr<=width; pr++)
{
if(pr ==1 )
cout<<" "<<(total-row+2)<<" ";
else if(pr ==width)
cout<<" "<<(width+row-1)<<" ";
else
cout<<" "<<" "<<" ";
}
cout<<"\n";
}
}
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'm working on an assignment that allows a user to enter integers (up to 20 entries) and displays a list of odd entries and even entries, when '0' is entered. The assignment requires the user to input a single integer per line.
I have managed to extract and segregate the odd and even entries, however the assignment requires that the odds be displayed on a single line, and the evens on another single line below that.
For example, if the user entered integers 1-9:
Odds: 1 3 5 7 9
Evens: 2 4 6 8
Currently, it returns:
Even: 2
Even: 4
Even: 6
Odd: 1
Odd: 3
Odd: 5
etc...
I am hoping that my program will even allow this, but I suspect the problem lies in the way I have set up the loops.
#include <iostream>
using namespace std;
bool isEven(int x) {
if ((x%2) == 0) {
return true;
} else {
return false;
}
}
int main(){
const int x = 20;
int list[x];
int counter;
cout<<"Enter up to 20 integers or press 0 to display list"<<endl;
for (counter=0; counter<x; counter++) { //main loop
cout<<"Enter number: ";
cin>>list[counter];
if (list[counter]==0) {
for (int i =0; i<counter; i++) {
if (isEven(list[i])==true) {
cout<<"Even: "<<list[i];
}
}
for (int j = 0; j<counter; j++) {
if (isEven(list[j])==false) {
cout<<"Odd: "<<list[j];
}
}
break;
}
}
return 0;
}
Split input and output to separate loops:
for (counter=0; counter<x; counter++) {
// input
}
for (counter=0; counter<x; counter++) {
// output
}
Print labels before going through each value and use \n to print a newline:
cout << "Even: ";
for (int i =0; i<counter; i++) {
if (isEven(list[i])==true) {
cout << list[i];
}
}
cout << "\nOdd: ";
for (int j = 0; j<counter; j++) {
if (isEven(list[j])==false) {
cout << list[j];
}
}
cout << "\n";
Alright, so I have this code which basically will prompt the user to enter a number and then according to that number the user entered, they will be asked (Please enter a number between 1 and 4)* the number the user chose. Then, their input will be compared to see if there is any match in the grid (rows and columns). Let me show you an example:
Please enter a number: 3
Please enter a number between 1 and 4: 2
Please enter a number between 1 and 4: 1
Please enter a number between 1 and 4: 2
Here is your grid:
(3x3 grid filled, since user entered 3, filled with random numbers)
4 2 4
3 1 1
4 3 3
Here is a sample of my code:
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <iomanip>
#include <time.h>
#include <ctime>
using namespace std;
double Atemp = 0;
double Utemp = 0;
double Working = 0;
double Total = 0;
char Answer = 'x';
int Umain;
void printGrid(int &Umain);
void fillIntArray(int array[], int size);
void reverseArray(int array[], int size);
void outputIntArray(int array[], int n);
void compareGrid(int &Atemp);
int main(){
int maxNum = 2;
int intArray[maxNum];
cout << "Please Enter numbers between 1 and 12: ";
cin >> Umain;
do{
if(Umain <=12){
fillIntArray(intArray, maxNum);
//outputIntArray(intArray, maxNum);
printGrid(Umain);
}
}while (Answer == 'y');
return 0;
}
void fillIntArray(int array[], int size){
do{
for (Utemp = Umain; Utemp > 0; Utemp--){
cout << "Please enter a number between 1 and 4: ";
cin >> Atemp;
if(Atemp <=4 && Atemp >=1){
for (int i = Atemp; i < Atemp; i++);
}else{
cout << "Not within limit \n";
}
}
}while (Answer == 'y');
}
void printGrid(int &Umain){
cout<<endl;
cout<<" ";
int i=1,j;
for(j = 0; j <= 4*Umain; j++){
if(j%4==2){
cout<<" ";
}
}
cout<<endl;
for(i = 0; i <= 2*Umain; i++){
for(j = 0; j <= 2*Umain; j++){
if(i%2==0){
if(j==0){
cout<<" ";
}
if(j%2==0){
cout<<" ";
}else{
cout<<"---";
}
}else{
if(j%2==0){
cout<<" | ";
}else cout<< (rand()%4+1);
}
}
if(i%2!=0){
cout<<" ";
}
cout<<endl;
}
cout<<" ";
for(j = 0, i = 1; j <= 4*Umain; j++){
if(j%4==2){
cout<< " ";
}
}
cout<<endl;
}
void compareGrid(int &Atemp){
}
For one thing, variable size arrays are not a part of C++. This part is wrong:
int maxNum = 2;
int intArray[maxNum];
Fix it by adding constexpr:
constexpr int maxNum = 2;
int intArray[maxNum];
Secondly, this part in general doesn't make sense and the semicolon at the end is really suspicions:
for (int i = Atemp; i < Atemp; i++); // why?
And assuming you have collected the user inputs in an array called Attempts of size 3, and intArray is the matrix of size 3x3, here's how you might compare attempts to the rows/columns of the so-called 2D array:
bool Contains() {
for (size_t iCol = 0; iCol != 3; ++iCol) {
for (size_t iRow = 0; iRow != 3; ++iRow) {
if(intArray[iCol][iRow] != Attempts[iRow]) {
return false;
}
}
}
return true;
}
Change places of iCol and iRow to check rows or columns
I have been working on a USACO problem and devised this (see below) algorithm for some test cases. However, for the input "brbrrrbbbrrrrrbrrbbrbbbbrrrrb", I am getting 9. I don't understand how this can be possible. Can anyone help me find the problem.
P.S: These are the outputs of first loop without any values in the second loop:
-10
-10
-10
3
3
5
-10
2
2
-10
4
4
-10
0
#include <iostream>
#include <vector>
using namespace std;
int main() {
string necklace;
cin >> necklace;
vector <int> neck;
int c_it = 0;
for(unsigned int i = 0; i < necklace.length(); i++){
if(necklace[i] == necklace[i+1] | 'w' == necklace[i+1]){
c_it++;
}
else{
if (c_it >= 1){
cout << c_it+1 << endl;
}
else{
cout << "-10" << endl;
}
c_it = 0;
}
}
int maximum = 0;
for(int i=0; i < neck.size(); i++){
for(int j=1; j<= neck.size(); j++){
int valueToCompare = neck[i] + neck[j];
if(valueToCompare > maximum){
maximum = valueToCompare;
}
i++;
j++;
}
}
cout << maximum;
}
The reason is you have an error is because of the "|" in your first if statement. It should be the boolean operator "||" instead.
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;
}