Tuesday, 25 July 2017

Handling the Patterns in C++


___________________________________________________________
These are often asked and the funny thing is we still don't pay much attention to this.
___________________________________________________________
Consider the Example:
*
**
***
****

Now , for a beginner it's a little bit challenging.

There are two ways to do this:
1. Just print everything with "COUT"
2. Using Loops(Your Logic)
________________________________________________________

The first can be done by anybody so lets start with second One.

for(int i=  0; i<=5 ;i++)
{
for(int j=0; j<i; j++)
{
cout<<"*";
}
cout<<"\n";
}
________________________________________________________

Explanation: 

This works from outer to inner. When i was 0, condition was true, loop goes inside, now j=0 and second condition is false so the loop comes outside and prints "\n"(A new Line).
Now the value of i=1, condition is true, loop goes inside, j=0, and the condition is true, so inner loop runs and prints "*".
Now the inner loop runs one more time and the j becomes 1 and now the condition is false, so inner loop terminates. back to the outer loop.
Like this the loop will go on until the i becomes greater than 5 and you will obtain an output. 

No comments:

Post a Comment