John Patrick Amata


my blog for algorithms
Dark/Light Mode:  
Share: 

Day 3

today

solved 2 problems at geeksforgeeks, problems are about printing certain patterns

General Notes for Patterns

These pattern problems are mostly an exercise of one’s ability to manipulate nested loops

Patter Problem 1

Link: https://practice.geeksforgeeks.org/problems/square-pattern/1

if n = 5, print:

* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
// https://practice.geeksforgeeks.org/problems/square-pattern/1
//{ Driver Code Starts
#include <bits/stdc++.h>

using namespace std;

// } Driver Code Ends
class Solution
{
public:
    void printSquare(int n)
    {
        // code here
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                cout << "* ";
            }
            cout << "\n";
        }
    }
};

//{ Driver Code Starts.

int main()
{
    int t;
    cin >> t;
    while (t--)
    {
        int n;
        cin >> n;

        Solution ob;
        ob.printSquare(n);
    }
    return 0;
}
// } Driver Code Ends

Notes: no special symmetry here, just that the input n is equal (counting from zeor based) to both colums and rows

Pattern Problem 2

Link: https://practice.geeksforgeeks.org/problems/right-triangle/

if n = 5, print:

* 
* * 
* * * 
* * * * 
* * * * *
//{ Driver Code Starts
#include <bits/stdc++.h>

using namespace std;

// } Driver Code Ends
class Solution {
  public:
    void printTriangle(int n) {
        // code here
        for (int i = 0; i < n; i++){
            for (int j = 0; j <= i; j++){
                cout << "* ";
            }
            cout << "\n";
        }
    }
};

//{ Driver Code Starts.

int main() {
    int t;
    cin >> t;
    while (t--) {
        int n;
        cin >> n;

        Solution ob;
        ob.printTriangle(n);
    }
    return 0;
}
// } Driver Code Ends

Notes: input is equal to the same amount of rows, and the column content is equal to the “count” of the current row.

Always mind the boundaries, particularly in the nested loop I used <= operator. If I used < then it wouldve made it off by one, e.g. an input n = 1 would’ve made it print a new line