How to print a rectangle of asterisks in C++ - c++

I have been told to ask the user to input how many rows and columns for a rectangle they would like to print and in what symbol they want it. I am unaware as to how to do this and all my google searching only got me as far as printing one row. Directions dictate that the rows should be 3 and the columns should be 7 with the character '$'. I'm still a beginner so please go easy on me. This is what I have:
#include <iostream>
#include <iomanip>
using namespace std;
void PrintChar(int row = 5, int column = 10, char symbol = '*');
int main()
{
int rows, columns;
char symbol;
cout << "How many rows and columns do you want, and with what symbol (default is *) ?" << endl;
cin >> rows >> columns >> symbol;
PrintChar(rows, columns, symbol);
}
void PrintChar(int row, int column, char symbol)
{
for (int y = 1; y <= column; y++)
{
cout << symbol;
}
That prints out a full line of the symbol and that's where my thinking stops. If you could help me with the final rows, that would be greatly appreciated.

This should do the trick. Added a newline to make it look like a rectangle.
#include <iostream>
#include <iomanip>
using namespace std;
void PrintChar(int row = 5, int column = 10, char symbol = '*');
int main() {
int rows, columns;
char symbol;
cout << "How many rows and columns do you want, and with what symbol (default is *) ?" << endl;
cin >> rows >> columns >> symbol;
PrintChar(rows, columns, symbol);
return(0);
}
void PrintChar(int row, int column, char symbol) {
for (int y = 1; y <= column; y++) {
for (int x = 1; x <= row; x++) {
cout << symbol;
}
cout << endl;
}
}

First, int main() should have a return statement.
There should be 2 nested for loops inside PrintChar, outer one for the rows and inner one for the columns, like:-
for (int x = 1; x <= rows; x++)
{
cout << endl;
for (int y = 1; y <= columns; y++)
{
cout << symbol;
}
}

Using nested loop you can achieve that.
void PrintChar(int row, int column, char symbol)
{
for (int x = 0; x < row; x++)
{
for (int y = 1; y <= column; y++)
{
cout << symbol;
}
cout << endl;
}
}

Seems as a basic star patterns looping exercise. Use nested loops to print the required pattern
for(i=1; i<=n; i++)
{
for(j=1; j<=m; j++)
{
cout<<"*";
}
cout<<"\n";
}
Here n is the number of rows and m is number of columns each row.

Related

Reversing Rectangle character after certain height

I am stuck in some tricky part. I have to reverse the rectangle character after certain height in c++ like below
111111111
122222221
123333321
123333321
122222221
111111111
in above i have to reverse rectangle character after height 3. My code works well in for first three rows but it didn't work for reversing. Input Rows 6 and Columns 9. Can any one tell where i am doing in my code. Below is my code
void Rectangle(int rows, int cols){
int mid = rows / 2, midcol = cols / 2;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= cols; j++) {
if (i > j)
{
if (i <= mid)
{
cout << j;
}
else if (j < midcol)
{
cout<< j;
}
else if (j == midcol)
{
cout<<cols - j - 1;
}
else
{
cout<<cols - j;
}
}
else if (i > cols - j)
{
cout<< cols - j + 1;
}
else
{
cout<< i;
}
}
cout << endl;
}
}
int main() { // Get the number
int row;
int columns;
cout<<"plase enter a Row height:";
cin >> row;
cout<<"plase enter a Columns:";
cin >> columns;
Rectangle(row, columns);
system("pause");
return 0;
}
We can observe the following.
Up to the mid column, the values are the column values, but not higher then the row values.
Over the middle column the column numbers are revered. What does this mean? If you have 10 columns and want to reverse it, then you have to subtract the column number from the width 10. So
10-6 = 4
10-7 = 3
10-8 = 2
10-9 = 1
10-10 = 0;
The same is valid for the rows.
So, for normal columns (< middle value). the column number
For column numbers above the middle, the reversed column number (see above)
But not bigger then the limited row value
The limited row value is calculated as per the above scheme
In my demo program I use a std::vector<std::vector<int>> to store the values. Calculated values start with 0. So I add 1 for each value add the end.
Please see:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
#include <cmath>
void showRectangle(const size_t height, const size_t width) {
std::vector lines{ height, std::vector(width, 0U) };
// Calculate the vales in the middle
const size_t midHeight{ static_cast<size_t>(std::ceil(height / 2.0)) };
const size_t midWidth{ static_cast<size_t>(std::ceil(width / 2.0)) };
// Iterate over all rows and columns
for (size_t row{ 0U }; row < height; ++row) {
for (size_t column{ 0U }; column < width; ++column) {
// Calculate the vaule for row and column
lines[row][column] = (std::min((column >= midWidth) ? (width - column-1) : column,
(row >= midHeight) ? (height - row - 1) : row)) +1 ;
}
}
// Show output
for (const std::vector<size_t>& vi : lines) {
std::copy(vi.begin(), vi.end(), std::ostream_iterator<size_t>(std::cout));
std::cout << "\n";
}
}
int main() {
// Explain the user that he has to enter the height in rows
std::cout << "\nEnter the height of the rectangle in rows: ";
// Get the height. And check, if input worked
if (size_t height{}; std::cin >> height) {
// Explain the user that he has to enter the width in columns
std::cout << "Enter the width of the rectangle in columns: ";
if (size_t width{}; std::cin >> width) {
// SHow result
std::cout << "\n\nResulting rectangle:\n\n";
showRectangle(height, width);
}
else {
std::cerr << "\n*** Error: wrong input for width\n";
}
}
else {
std::cerr << "\n*** Error: wrong input for height\n";
}
}

Checking for validity in 2d array

so i am creating a sudoku validity checker program in C++. the program takes in a csv file with an already completed sudoku board. the program is supposed to read the file line by line and put the numbers into a 2d array (which it's doing just fine). i'm getting stuck on the checking whether or not there are any duplicate numbers in a row (i assume that if i can get this working then the columns should be fairly similar). i know how the algorithm is supposed to work in my head but i just can't seem to get it into code.
Algorithm:
1) look at each row and check for numbers 1 through 9 making sure that they only appear once (if at all)
2) if a duplicate is found (which means that some number is missing) tell the user at what row and column the error was found.
3) otherwise move on to the next row and do it again
i think that it's supposed to be a for loop running this but it's been a long time since i've coded in C++ and nothing on the internet has been very helpful to me.
Any help is appreciated.
Here is my code so far:
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <thread>
using namespace std;
int *board[9];
int row, col;
void printBoard();
void is_row_ok();
int main()
{
for (int i = 0; i < 9; ++i)
{
board[i] = new int[9];
}
printBoard();
is_row_ok();
cout << endl;
return 0;
}
void printBoard()
{
string line;
string val;
ifstream myFile("Testfile1.txt");
for (int row = 0; row < 9; ++row)
{
string line;
getline(myFile, line);
if (!myFile.good())
break;
stringstream iss(line);
cout << endl;
for (int col = 0; col < 9; ++col)
{
string val;
getline(iss, val, ',');
if (!iss.good())
break;
stringstream convertor(val);
convertor >> board[row][col];
cout << board[row][col] << " ";
}
}
cout << endl;
cout << endl;
}
void is_row_ok()
{
bool found = false;
int i, j;
for (int i = 0; i < 10; ++i) //<------ edit starts here
{
int counter = 0;
for (int j = 0; j < 9; ++j)
{
if(board[row][j] == i)
{
cout << "Before " << counter << endl;
counter++;
cout << counter << endl;
}
if(counter > 1)
break;
}
}
}
The easiest way I can think of is 2 loops (one inside of another): 1 gets you through numbers 1 to 9 and the other goes through the elements of the row. Small tip with code.
for(int i=1;i<10;i++){
int counter =0;
for(int j=0;j<9;j++){
if(board[row][j] ==i)counter ++;
}
if(counter >1) break; //here you check that there´s only one number on the row.
}
Of course, there are other ways to do it, this one is quite basic and slow.
-------------------------------------EDIT-------------------------------------------
Your function should be bool in order to know if there´s repeated number or not.
bool is_row_ok(vector<vector<int> board)//I suggest you use vectors instead of arrays.
{
//i and j are declared on for, there´s no need to declare them again.
for (int i = 0; i < 10; ++i)
{
int counter = 0;
for (int j = 0; j < 9; ++j)
{
if(board[row][j] == i)counter++;
if(counter > 1)return false;
}
}
return true;
}
Now you call this function on main. If function returns true, everything is ok, if it returns false, you have a repeated number.
int main(){
if(is_row_ok(board)cout<<"No number repeated"<<endl;
else cout << "Number repeated"<<endl;
return 0;
}
I think the easiest way is to use std::sort + std::unique as unique returns iterator to the new end of range.
#include <algorithm>
using namespace std;
int main()
{
int n[15] = { 1, 5, 4, 3, 6, 7, 5, 5, 5, 4, 2, 3, 9, 8, 9 };
int* end = n + 15;
sort(n, n + 15);
bool has_no_duplicates = (unique(n, n + 15) == end);
return 0;
}
This is just an example but you should get the idea.

Printing a square of zeros based off of squared integers--different from asterisks c++ [duplicate]

I have been told to ask the user to input how many rows and columns for a rectangle they would like to print and in what symbol they want it. I am unaware as to how to do this and all my google searching only got me as far as printing one row. Directions dictate that the rows should be 3 and the columns should be 7 with the character '$'. I'm still a beginner so please go easy on me. This is what I have:
#include <iostream>
#include <iomanip>
using namespace std;
void PrintChar(int row = 5, int column = 10, char symbol = '*');
int main()
{
int rows, columns;
char symbol;
cout << "How many rows and columns do you want, and with what symbol (default is *) ?" << endl;
cin >> rows >> columns >> symbol;
PrintChar(rows, columns, symbol);
}
void PrintChar(int row, int column, char symbol)
{
for (int y = 1; y <= column; y++)
{
cout << symbol;
}
That prints out a full line of the symbol and that's where my thinking stops. If you could help me with the final rows, that would be greatly appreciated.
This should do the trick. Added a newline to make it look like a rectangle.
#include <iostream>
#include <iomanip>
using namespace std;
void PrintChar(int row = 5, int column = 10, char symbol = '*');
int main() {
int rows, columns;
char symbol;
cout << "How many rows and columns do you want, and with what symbol (default is *) ?" << endl;
cin >> rows >> columns >> symbol;
PrintChar(rows, columns, symbol);
return(0);
}
void PrintChar(int row, int column, char symbol) {
for (int y = 1; y <= column; y++) {
for (int x = 1; x <= row; x++) {
cout << symbol;
}
cout << endl;
}
}
First, int main() should have a return statement.
There should be 2 nested for loops inside PrintChar, outer one for the rows and inner one for the columns, like:-
for (int x = 1; x <= rows; x++)
{
cout << endl;
for (int y = 1; y <= columns; y++)
{
cout << symbol;
}
}
Using nested loop you can achieve that.
void PrintChar(int row, int column, char symbol)
{
for (int x = 0; x < row; x++)
{
for (int y = 1; y <= column; y++)
{
cout << symbol;
}
cout << endl;
}
}
Seems as a basic star patterns looping exercise. Use nested loops to print the required pattern
for(i=1; i<=n; i++)
{
for(j=1; j<=m; j++)
{
cout<<"*";
}
cout<<"\n";
}
Here n is the number of rows and m is number of columns each row.

C++,console, cout Vector in 2D array

I am relative new to C++ so please have mercy. I am trying to cout the start and end of a "vector" in a 2D array 40*20. but the "b" dont get placed in with the last 2 for loops. In the end i want to display 2 vectors with the second starting at [0][0] and going the same direction as the one typed in by the user. I also don't know how to, get the b's to be from the starting point of the line to the end point of the line and not just start and ending point. But the main problem is that the x is not changed with the b.
Thanks for your help.
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
int vectorsx;
int vectorsy;
int vectorendx;
int vectorendy;
char display[40][40];
char row;
char column;
typedef struct
{
double x;
double y;
}punkt;
typedef struct
{
punkt PA;
punkt PE;
}vector;
void query()
{
cout << "Startpunkt x:";
cin >> vectorsx;
cout << "Startpunkt y:";
cin >> vectorsy;
cout << "Endpunkt x:";
cin >> vectorendx;
cout << "Endpunkt y:";
cin >> vectorendy;
}
int main()
{
query();
vector v;
v.PA.x = vectorsx;
v.PA.y = vectorsy;
v.PE.x = vectorendx;
v.PE.y = vectorendy;
vector v2;
v2.PA.x = 0;
v2.PA.y = 0;
v2.PE.x = v.PE.x - v.PA.x;
v2.PE.y = v.PE.y - v.PA.y;
for (int row = 0; row < 20; row++)
{
for (int column = 0; column < 40; column++)
{
display[row][column] = 'x';
}
}
for (int row = 0; row < 20; row++)
{
for (int column = 0; column < 40; column++)
{
cout << display[row][column];
}
cout << endl;
}
for (row = 0; row < 20; row++)
{
for(column = 0; column < 40;column++)
{
display[vectorsx][vectorsy] = 'b';
}
}
for (row = 0; row < 20; row++)
{
for (column = 0; column < 40; column++)
{
display[vectorendx][vectorendy] = 'b';
}
}
system("Pause");
return 0;
}
You set all elements of display to 'x'. Then you print the contents of dispaly. And then you change the contents of two elements to b. You don't print the array again.
Do the printing after you change the arrays.
You also don't need the loops for the changes, you are changing the same element 800 times.

how to create a pyramid using for loop in c++

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;
}
}