can anyone tell me how to write a programme to print numbers in following fashion

1
0 1
1 0 1
0 1 0 1
1 0 1 0 1

Dani AI

Generated

asked for a program that prints an increasing triangle of alternating 1s and 0s; and pointed out no attempt was shown, and noted the repetition. Below is a short explanation, a couple of tips, and minimal implementations in Python and C.

Concept: row k (1..n) contains k numbers. Odd rows start with 1, even rows start with 0. For each row set val = k % 2 and print val, flipping it (val ^= 1) for each next position. Avoid trailing spaces by building each row as a string (Python join) or by printing the space only before subsequent numbers (C).

Python (concise, no trailing spaces):

def print_triangle(n):
    for k in range(1, n + 1):
        start = k % 2
        print(' '.join(str((start + j) % 2) for j in range(k)))

if __name__ == "__main__":
    n = int(input().strip() or 0)
    if n > 0:
        print_triangle(n)

C (reads n, efficient per-row printing):

#include <stdio.h>

int main(void) {
    int n;
    if (scanf("%d", &n) != 1 || n <= 0) return 0;
    for (int k = 1; k <= n; ++k) {
        int val = k % 2;
        for (int j = 0; j < k; ++j) {
            if (j) putchar(' ');
            putchar('0' + val);
            val ^= 1;
        }
        putchar('\n');
    }
    return 0;
}

Notes: time and output size are O(n^2). Use the join approach in Python for speed and to avoid manual spacing. In C, toggling with XOR (val ^= 1) is simple and fast.

Recommended Answers

All 3 Replies

post the code what ever you have done so far.

I think I just had daja vu.

commented: Heh, it happens a lot ;) +36
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.