Given an integer n. You need to recreate the pattern given below for any value of N. Let's say for N = 5, the pattern should look like as below:
1
0 1
1 0 1
0 1 0 1
1 0 1 0 1
Print the pattern in the function given to you.
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
//Function to print pattern11
void pattern11(int n) {
// First row starts by printing a single 1.
int start = 1;
// Outer loop for the no. of rows
for (int i = 0; i < n; i++) {
/* if the row index is even then 1
is printed first in that row.*/
if (i % 2 == 0) start = 1;
/* if odd, then the first 0
will be printed in that row*/
else start = 0;
/* We alternatively print 1's and 0's
in each row by using inner for loop*/
for (int j = 0; j <= i; j++) {
cout << start << " ";
start = 1 - start;
}
/*As soon as the numbers for each
iteration are printed, we move to the
next row and give a line break */
cout << endl;
}
}
};
int main() {
int N = 5;
//Create an instance of Solution class
Solution sol;
sol.pattern11(N);
return 0;
}
class Solution {
// Function to print pattern11
void pattern11(int n) {
// First row starts by printing a single 1.
int start = 1;
// Outer loop for the number of rows
for (int i = 0; i < n; i++) {
/* If the row index is even, start
with 1; if odd, start with 0*/
if (i % 2 == 0) start = 1;
else start = 0;
/* Alternatively print 1's and 0's
in each row by using inner for loop*/
for (int j = 0; j <= i; j++) {
System.out.print(start+" ");
start = 1 - start;
}
// Move to the next row and give a line break
System.out.println();
}
}
public static void main(String[] args) {
int N = 5;
// Create an instance of Solution class
Solution sol = new Solution();
sol.pattern11(N);
}
}
class Solution:
# Function to print pattern11
def pattern11(self, n):
# First row starts by printing a single 1.
start = 1
# Outer loop for the number of rows
for i in range(n):
""" If the row index is even, start
with 1; if odd, start with 0"""
if i % 2 == 0:
start = 1
else:
start = 0
""" Alternatively print 1's and 0's
in each row by using inner for loop"""
for j in range(i + 1):
print(start, end=" ")
start = 1 - start
# Move to the next row and give a line break
print()
if __name__ == "__main__":
N = 5
# Create an instance of Solution class
sol = Solution()
sol.pattern11(N)
class Solution {
// Function to print pattern11
pattern11(n) {
// First row starts by printing a single 1.
let start = 1;
// Outer loop for the number of rows
for (let i = 0; i < n; i++) {
/* If the row index is even, start
with 1; if odd, start with 0 */
if (i % 2 === 0) start = 1;
else start = 0;
/* Alternatively print 1's and 0's
in each row by using inner for loop*/
let row = "";
for (let j = 0; j <= i; j++) {
row += start+" ";
start = 1 - start;
}
// Output the row
console.log(row);
}
}
}
let N = 5;
// Create an instance of Solution class
let sol = new Solution();
sol.pattern11(N);