void nForest(int n) {
// Write your code here.
for (int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cout<<"* ";
}
cout<<endl;
}
}
Problem of the day
Sam is making a forest visualizer. An N-dimensional forest is represented by the pattern of size NxN filled with ‘*’.
For every value of ‘N’, help sam to print the corresponding N-dimensional forest.
Example:Input: ‘N’ = 3
Output:
* * *
* * *
* * *
The first and only line contains an integer, ‘N’.
Output format:
Print the pattern as specified.
1 <= N <= 25
Time Limit: 1 sec
3
* * *
* * *
* * *
For N = 3, fill all the rows and columns in 3x3 matrix with ‘*’.
1
*
4
* * * *
* * * *
* * * *
* * * *
Think about how to use nested loops to iterate through each row and column of the ‘N x N’ -dimensional matrix.
Approach:
The solution to the problem lies in just iterating to all the NxN cells of the pattern and print every cell with ‘*’.
The steps are as follows :
Function void nForest(int ‘N’)
O(NxN)
There are two nested loops and both are running exactly N times, so time complexity would be the order of NxN.
Hence the time complexity is O(NxN).
O(1).
Since we are using constant extra space.
Hence the space complexity is O(1).
Interview problems
cpp solution
void nForest(int n) {
// Write your code here.
for (int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cout<<"* ";
}
cout<<endl;
}
}
Interview problems
c++ code
void nForest(int n) {
for (int i=0;i<n;i++){
for (int j=0;j<n;j++){
cout<<"* ";
}
cout<<endl;
}
}Interview problems
Pattern
void nForest(int n) {
// Write your code here.
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cout<< "* ";
}
cout<< endl;
}
}
Interview problems
Solution in java
public class Solution {
public static void nForest(int n) {
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
System.out.print("* ");
}
System.out.println("\n");
}
}
}
Interview problems
solution in cpp
void nForest(int n) {
// Write your code here.
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cout<<"*"<<" ";
}
cout<<endl;
}
}
Interview problems
N-Forest
def nForest(n:int) ->None:
# Write your solution here.
for i in range(n):
for j in range(n):
print("*",end=" ")
print()
pass
Interview problems
N-Forest Solution in Java
public class Solution {
public static void nForest(int n) {
// Write your code here
for(int i=1; i<=n; i++){
for(int j=1; j<=n; j++){
System.out.print("* ");
}
System.out.println();
}
}
}Interview problems
N FOREST
void nForest(int n) {
// Write your code here.
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cout<<"*";
}
cout<<endl;
}
};
Interview problems
n- forest simple cpp
void nForest(int n) {
// Write your code here.
for(int r=0;r<n;r++){
for(int j=0;j<n;j++){
cout<< "* ";
}
cout<<"\n";
}
}