Click here to Skip to main content
15,892,797 members
Please Sign up or sign in to vote.
2.33/5 (2 votes)
See more:
I needed code for this pattern.

1 2
2 3
3 4
4 5

I tried it , but was not able to make it.


What I have tried:

#include<stdio.h>

void main() {
    int i,j;
 
    for(i=1; i<=5; i++){
        for(int j=i;j<=5;j++)
        {
     printf("%d ",j);

        
}
printf("\n");
    }
    

}
Posted
Updated 12-Sep-18 20:37pm

You should review your loops. Try
C
#include <stdio.h>

int main()
{
  int i;

  for (i=1; i<=4; i++)
  {
    int j;
    for (j=0;j<=1;j++)
    {
      printf("%d ",(i+j));
    }
    printf("\n");
  }

  return 0;
}
 
Share this answer
 
Learn to indent properly your code, it show its structure and it helps reading and understanding. It also helps spotting structures mistakes.
C++
#include<stdio.h>

void main() {
  int i,j;
  for(i=1; i<=5; i++){
    for(int j=i;j<=5;j++)
    {
      printf("%d ",j);
    }
    printf("\n");
  }
}

Professional programmer's editors have this feature and others ones such as parenthesis matching and syntax highlighting.
Notepad++ Home[^]
ultraedit[^]
-----
Learn to analyze problems, start simple
This code will print the first column:
C++
#include<stdio.h>

void main() {
  int i;
  for(i=1; i<=4; i++){
    printf("%d ",i);
    printf("\n");
  }
}

then add the second column
C++
#include<stdio.h>

void main() {
  int i;
  for(i=1; i<=4; i++){
    printf("%d ",i); // first column
    printf("%d",i+1);// second column
    printf("\n");
  }
}

- Learn one or more analyze methods, E.W. Djikstra/N. Wirth Stepwize Refinment/top-Down method is a good start.
Structured Programming.pdf[^]
https://en.wikipedia.org/wiki/Top-down_and_bottom-up_design[^]
https://en.wikipedia.org/wiki/Structured_programming[^]
https://en.wikipedia.org/wiki/Edsger_W._Dijkstra[^]
https://www.cs.utexas.edu/users/EWD/ewd03xx/EWD316.PDF[^]
 
Share this answer
 
C++
for (int i = 1; i < 5; ++i)
    cout << i << " " << i + 1 << endl;

or if you insist on having two loops:
C++
for (int i = 1; i < 5; ++i)
{
    for (int j = i; j < i + 2; ++j)
    {
         cout << j;
         cout << " ";
    }
    cout << endl;
}
 
Share this answer
 
on more try for your homework
C++
#include<stdio.h>

void main() {
  int;
  for(int i=1; i<5; i++) {
    printf("%d %d\n",i,i+1); // complete line
  }
  return 0;
}
it should run significant faster ;-)
 
Share this answer
 
Comments
Richard Deeming 13-Sep-18 14:57pm    
Surely the fastest solution would be:
printf("1 2");
printf("2 3");
printf("3 4");
printf("4 5");

:)

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