Click here to Skip to main content
15,880,967 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
write a program to print given pattern using for loop
4 8
16 32 64
128 256 512 1024

What I have tried:

  int main()                  
{ int a=2,n=5;

    for(int i=1;i<=n;++i){
    for(int j=1;j<=i;++j){
        printf("%d ",a++);

    return 0;
Updated 7-Nov-22 19:56pm

You don't need twop loops: one will do it.

Think about it: all you are doing is printing the powers of two with some spacing. So why use two loops? Why not one loop to print each power, and a test to see if you need to print a newline?
All you need is a count of values in the row so far (inRow), and a "number to print in this row" (nextRowAt). When you print the number you increment inRow and compare it to nextRowAt. If it matches, print a new line, increment nextRowAt and reset inRow for next time.

I'd probably also use a Shift operator instead of pow each time.
Share this answer
How do I solve this problem

Your code already print the correct shape with wrong values.
Look at the sequence of values you need:
2 4 8 16 32 64 128 256 512 1024

How each value evolve for previous one. should be easy.

Your code do not behave the way you expect, or you don't understand why !

There is an almost universal solution: Run your code on debugger step by step, inspect variables.
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't know what your code is supposed to do, it don't find bugs, it just help you to by showing you what is going on. When the code don't do what is expected, you are close to a bug.
To see what your code is doing: Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.

Debugger - Wikipedia, the free encyclopedia[^]

Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]

1.11 — Debugging your program (stepping and breakpoints) | Learn C++[^]

The debugger is here to only show you what your code is doing and your task is to compare with what it should do.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900