Click here to Skip to main content
15,949,686 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
The pattern is as follows:

1. _ _ _ *
2. _ _ * *
3. _ * * *
4. * * * *

[Ignore numbers: just used them to increase readiblity, and underscores are spaces here for representation.]

Well its quiet easy to do it with 2 for or while loops , but my friend challenged me to it with only 1 loop.And i have to create a general program for it , so that it runs for not only 4 but 5 or 6 too.

Well i tried and tried , and till now i have reached this far:
C++
int a=1;
int times=4; // no. of times a line , 4 here but user can enter anything
int totalelements=times*times;
int n=1;
int breakpoint=(times*n)-(n-1);

// breakpoints are the first occurences of * like 4th position in 1st line, 7th in 2nd line..


while(a<(totalelements+1))

{

if (breakpoint==a)
{cout<<"*"; 
n++;                            //to increment n for next value in breakpoint formula
breakpoint=(times*n)-(n-1); }   //get new breakpoint formula

else cout<<" ";

if(a%times==0) { cout<<endl;} // for printing nextline every 4th element here

}



The expected output is :

1. _ _ _ *
2. _ _ * _
3. _ * _ _
4. * _ _ _

So the thing i am doing wrong is : i am able to find out breakpoint pattern for it , but it prints stars only at those breakpoints , not after that.
How should i do that , to print those stars after that breakpoint

one thing i can relate is the no. of stars being printed is the value of n at that time, so how should i link it?

The program must use only 1 loop , any no. of variables , and no goto statement .
Posted

1 solution

I think you may simplify the matter just recognizing the bidimensional nature of the required pattern, that is you have rows an columns:
C++
#include <iostream>
using namespace std;
int main()
{
    int n=4; // no. of times a line , 4 here but user can enter (almost :-) ) anything 
    for (int i=0; i<n*n; ++i)
    {

         int r = i/n; // row number
         int c = i%n; // column number

         cout << (c < n-1-r ? ' ':'*');
         if (c==n-1) cout << endl;
    }
}
 
Share this answer
 
Comments
Abhinav Gauniyal 25-Sep-13 16:46pm    
How do you do that? Answer: Experience , as i assume , BTW thanks Sir :)
CPallini 25-Sep-13 17:01pm    
Yes, experience, I suppose. You are welcome.
Sergey Alexandrovich Kryukov 25-Sep-13 17:03pm    
5ed.
—SA
CPallini 25-Sep-13 17:10pm    
Thank you, Sergey.
Maciej Los 25-Sep-13 18:22pm    
Agree!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900