Subscribe to C++ FunSchool        RSS Feed
-----

[C++] Answer to questions on Nested Loops

Icon Leave Comment
Q1. WAPT: show the following pattern

_______$
______$$
_____$$$
____$$$$
___$$$$$
__$$$$$$
_$$$$$$$
$$$$$$$$

(If the user input is 8)

#include<iostream.h>
int main()
{
    int n;
    cin >> n;
    
    for (int i=1; i<=n; i++) //For number of lines
    {
        for (int j=1; j<=(n-i) ;j++)
        { 
            cout << "_";
        }
        
        for (int k=1; k<=i; k++)
        {
            cout << "$";
        }
        
    cout << endl;
    }
    
    return 0;
}



We take 3 loops; one for line number, one for the number of '_' and one for the number of '$' symbol. If we look closely, in line 1, we have 1 '$' and (8-1) '_'. In line 2, we have 2 '$' and (8-2) '_'. In general, line i has i '$' and (n-i) '_' symbols. Hence the pattern follows upto the n'th line.

If there are any questions or doubts, feel free to email me at: navking.venkat7@gmail.com

0 Comments On This Entry

 

Trackbacks for this entry [ Trackback URL ]

There are no Trackbacks for this entry

September 2014

S M T W T F S
 123456
78910111213
1415 16 17181920
21222324252627
282930    

Tags

    Recent Entries

    Search My Blog

    0 user(s) viewing

    0 Guests
    0 member(s)
    0 anonymous member(s)

    Categories