Printing * pattern in C++ - c++

I am trying to print a pattern like this
*******
* *
* *
* *
* *
* *
*******
In this it should look like an empty box.
but somehow I am not getting even closer
I coded this so far
#include <iostream>
using namespace std;
int main( int argc, char ** argv ) {
for(int i=1;i<=7;i++)
{
for(int j=1;j<=7;j++)
{
if(j==1||j==7)
printf("*");
else printf(" ");
}
printf("\n");
}
return 0;
}
and my output is
* *
* *
* *
* *
* *
* *
* *
it will be good to have for loop only

if(j==1||j==7)
printf("*");
else printf(" ");
This logic works for all rows except first and last one. So you have to consider row value and make special check for first and last rows. These two do not have spaces.
[Assuming it's a homework, I'm giving just a hint. You almost have done it, above hint should be enough to get this working.]

Your if condition simply needs to be:
if (i==1 || i==7 || j==1 || j==7)
That is, you need to check whether you're on either the first or last rows as well as either the first or last columns, and then print a *.

You are very close. The problem is in this line:
if(j==1||j==7)
Change it so that it also takes into account the top and bottom rows.
Good luck

You need to behave differently during first and last row:
int W = 7, H = 7;
for(int i=0;i<=H;i++)
{
for(int j=0;j<=W;j++)
{
// if row is the first or row is the last or column is the first of column is the last
if (i == 0 || i == H-1 || j == 0 || j == W-1)
printf("*");
else printf(" ");
}
printf("\n");
}

This function will work fine:
#include <iostream>
#include <string>
void printBox(int width, int height) {
if (width < 2 or height < 1) return;
for (int i = 1; i <= height; i++) {
if (i == 1 or i == height) {
std::string o(width, '*');
std::cout << o << std::endl;
} else {
std::string o(width-2, ' ');
o = '*' + o + '*';
std::cout << o << std::endl;
}
}
}
It can be used as:
printBox(2, 2);
which prints:
**
**
Or as:
printBox(6, 4);
which prints:
******
* *
* *
******

Since I'm not expert in programming, I came up with this simple code:
#include <stdio.h>
int main(void)
{
int i,j,k,n;
printf("Enter no of rows : \n");
scanf("%d", &n);
for(i=0; i<n; i++)
{
if(i == 0 || i == (n-1))
{
for(j=0; j <n-1; j++)
printf("*");
}
else
{
for(k=0; k<n; k++)
{
if (k == 0 || k == (n-2))
printf("*");
else
printf(" ");
}
}
printf("\n");
}
return 0;
}

for(int j=1;j<=7;j++)
{
if(j==1||j==7)
printf("*******\n");
else
printf("* *\n");
}
printf("\n");

You are treating all lines equally and ignoring the fact that the first and last line must be handled differently. You need something like
if (i == 1 || i == 7)
{
for (j=1;j<7;j++) printf("*");
printf("\n");
}
else { /* your routine */ }

This is what your code should look like:
#include <iostream>
using namespace std;
int main( int argc, char ** argv ) {
for(int i=1;i<=7;i++)
{
for(int j=1;j<=7;j++)
{
if(j == 1 || j == 7)
printf("*");
else if (i == 1 || i == 7 ) //added this check
printf ("*");
else printf(" ");
}
printf("\n");
}
return 0;
}
Live example

You'll need a nested loop. Because you've two options in between their, you'll need two nested loops. One for spaces and one for the filling '*' in iteration 1 and 7 (0 and 6).
Print the line 1 and 7 with a '*' filling the boundary stars.
Using
if (i == 0 || i == 7) // in-case you're initializing i with 0
// loop for printf ("*");

As others said, you need to handle first and last row. One way to build each line is to make use of one of string constructors, so you don't need to write the inner loop.
#include <string>
#include <iostream>
using namespace std;
int main()
{
int height = 7, width = 7;
for( int i=0; i<height; i++ )
{
char c = (i == 0 || i == height-1) ? '*' : ' ';
string line(width, c);
line[0] = line[width-1] = '*';
cout << line << endl;
}
return 0;
}

#include <iostream>
#include<iomanip>
using namespace std;
main()
{
int Width;
char MyChar;
int LCV; //Loop control
int LCVC, LCVR; //Loop control for LCVC=Columns LCVR=Rows
cout<<"\nEnter Width: "; cin>>Width;
cout<<"\nEnter a Character: "; cin>>MyChar;
for (LCV=1;LCV<=Width;LCV++)
{cout<<MyChar;}
cout<<endl;
for(LCVC=1;LCVC<=Width;LCVC++)
{ cout<<MyChar<<setw(Width-1)<<MyChar<<endl;
}
for (LCV=1;LCV<=Width;LCV++)
{cout<<MyChar;}
cout<<endl;
system("pause");
}
/*
Enter Width: 6
Enter a Character: #
######
# #
# #
# #
# #
# #
# #
######
Press any key to continue . . .
*/

Print this pattern
enter a number=each number for example 23517
**
*
Then
**
*
*****
*
*******
then
** *
* *
***** *
and
*
*
*
*
*

I have come up with a simple solution. You can keep it very simple rather than using char array pointers that you used.
#include <iostream>
using namespace std;
int main() {
int rows = 7;
for(int i = 1; i<=rows;i++){
if(i == 1 || i == rows){
cout<<"*******"<<endl;
}else{
cout<<"* *"<<endl;
}
}
return 0;
} // This code outputs 7 rows with 7 characters in 1st and 7 line each and 1 each character at the start and last position of the remaining rows
But if you want a custom number of rows, you can try out the following code
#include <iostream>
using namespace std;
int main() {
int rows;
cout<<"Enter the number of rows: ";
cin>>rows; // gets input rows from the user
for(int i = 1; i<=rows;i++){
if(i == 1 || i == rows){
cout<<"*******"<<endl;
}else{
cout<<"* *"<<endl;
}
}
return 0;
}

you can add:
`if(i==0 || i==6)
{
cout<<"*";
}`

Related

printing the below pattern using just one loop

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

c++ convert texts like one two three as 123 and zero one two as 12 in a file and sort them like 12 123

convert texts like one two three as 123 and zero one two as 12 in a file and sort them like 12 123 i am fetching the input from a file which contains this input .i got them printed but i cant sort them..i used atoi function to convert into number but then it prints 0. please help.
one two three
five seven
zero one two
three two one
#include<iostream>
#include<string.h>
#include<fstream>
#include <stdlib.h>
using namespace std;
int findno(char * a);
ifstream fin;
int i=0,k=0,j=0,count=0,s=0;
char ar[100],ch,str[100],no[100][100];
int main(int argc,char * argv[])
{
fin.open(argv[1]);
fin.getline(ar,100);
while(i<strlen(ar))
{
if(ar[i]!=' ')
{
str[k++]=ar[i];
i++;
if(i==strlen(ar))
{
fin.getline(ar,100);
no[s][j++]=findno(str);
cout<<(int)no[s][j-1]<<"\n";
i=0;
k=0;
j=0;
s++;
}
continue;
}
if(ar[i]==' ')
{
no[s][j++]=findno(str);
cout<<(int)no[s][j-1];
i++;
k=0;
}
}
cout<<atoi(no[0])<<" ";
fin.close();
return 0;
}
int findno(char * a)
{
if(a[0]=='z')
return 0;
if(a[0]=='o')
return 1;
if(a[0]=='t' && a[1]=='w')
return 2;
if(a[0]=='t' && a[1]=='h')
return 3;
if(a[0]=='f' && a[1]=='o')
return 4;
if(a[0]=='f' && a[1]=='i')
return 5;
if(a[0]=='s' && a[1]=='i')
return 6;
if(a[0]=='s' && a[1]=='e')
return 7;
if(a[0]=='e')
return 8;
if(a[0]=='n')
return 9;
}
zero one two as 12
You can use flag signaling about presents non-zero character or not, as on example below. Set flag to false before reading next word, and set to true, if you found some non-zero character.
bool flag = false;
int tmp;
while(i<strlen(ar))
{
if(ar[i]!=' ')
{
str[k++]=ar[i];
i++;
if(i==strlen(ar))
{
fin.getline(ar,100);
tmp=findno(str);
if (flag || (tmp > 0))
{
no[s][j++] = tmp;
cout << tmp <<"\n";
}
i=0;
k=0;
j=0;
flag = false;
s++;
}
continue;
}
if(ar[i]==' ')
{
tmp=findno(str);
if (tmp > 0)
flag = true;
if (flag)
{
no[s][j++] = tmp;
cout << tmp;
}
i++;
k=0;
}
}

spoj (Ambiguous Permutations)

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

With how many loops can the following process be done in C++?

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

draw X letter shape using asterisk(*)

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