Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing * pattern in C++

Tags:

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

like image 300
shubh Avatar asked Nov 28 '22 08:11

shubh


2 Answers

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 *.

like image 32
Joseph Mansfield Avatar answered Dec 31 '22 12:12

Joseph Mansfield


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.]

like image 77
taskinoor Avatar answered Dec 31 '22 11:12

taskinoor