void triangle(int n) {
// Write your code here
for (int i=1;i<=n;i++){
for(int j=1;j<=i;j++){
cout<<i<<" ";
}
cout<<endl;
}
}
Problem of the day
Sam is making a Triangular painting for a maths project.
An N-dimensional Triangle is represented by the lower triangle of the pattern filled with integers representing the row number.
For every value of ‘N’, help sam to print the corresponding Triangle.
Example:Input: ‘N’ = 3
Output:
1
2 2
3 3 3
The first and only line contains an integer, ‘N’.
Output format:
Print the pattern as specified.
1 <= N <= 25
Time Limit: 1 sec
3
1
2 2
3 3 3
1
1
Iterate to all the cells.
Approach:
The solution to the problem lies in just iterating to all the NxN cells of the pattern and printing every cell in the lower triangle.
The steps are as follows :
Function void triangle(int ‘N’)
O(N*N), Where N is the dimension of the square matrix.
There are two nested loops, so time complexity would be the order of NxN.
Hence the time complexity is O(N*N).
O(1).
Since we are using constant extra space.
Hence the space complexity is O(1).
Interview problems
Cpp
void triangle(int n) {
// Write your code here
for (int i=1;i<=n;i++){
for(int j=1;j<=i;j++){
cout<<i<<" ";
}
cout<<endl;
}
}
Interview problems
cpp solution
void triangle(int n) {
// Write your code here
for(int i=1;i<=n;i++)
{
for(int j=0;j<i;j++)
{
cout<<i<<" ";
}
cout<<endl;
}
}Interview problems
solution in java
public static void nTriangle(int n) {
// Write your code here
for(int i=1; i<=n; i++){
for(int j=1; j<=i; j++){
System.out.print(i+" ");
}
System.out.println("\n");
}
}
Interview problems
solution
void triangle(int n) {
// Write your code here
for(int i = 0; i<n;i++){
for(int j=0;j<i+1;j++){
cout<<i+1<<" ";
}
cout<<endl;
}
}
Interview problems
Pattern
void triangle(int n) {
// Write your code here
for(int i=1;i<=n;i++){
for(int j=1;j<=i;j++){
cout<<i<<" ";
}
cout<<endl;
}
}
Interview problems
solution in cpp
void triangle(int n) {
// Write your code here
for(int i = 1; i <= n;i++){
for(int j = 1; j <=i; j++){
cout<<i<<" ";
}
cout<<endl;
}
}
Interview problems
Triangle
def triangle( n:int) ->None:
# Write your solution here.
for i in range(n):
for j in range(i+1):
print(i+1,end=" ")
print()
pass
Interview problems
Triangle Solution in Java
public class Solution {
public static void nTriangle(int n) {
// Write your code here
for(int i=1; i<=n; i++){
for(int j=1; j<=i; j++){
System.out.print(i+" ");
}
System.out.println();
}
}
}Interview problems
Best way to solve this problem
void triangle(int n) {
// Write your code here
int count=1;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(i>=j){
cout<<count<<" ";
}
else{
cout<<" ";
}
}
count++;
cout<<endl;
}
}
Interview problems
pattern triangle
void triangle(int n) {
for(int i = 1; i<=n; i++){
for(int j = 1; j<=i; j++){
cout<<i<<" ";
}
cout<<endl;
}
}