Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

For-loop pattern that increments the last column by 1

I am trying to make a for-loop program that prints the same digits or integers every row except the last column which is being incremented by 1.

Example:

     1 1 1 1 1 2

     2 2 2 2 2 3

     3 3 3 3 3 4

     4 4 4 4 4 5

Here is my code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

int main(){
int num,value;
scanf("%d", &num);

for(int i=1; i<=num; i++){
    for(int j=i; j < i+num; j++){
        value = i;
        printf("%d ", value);
    }

    printf("\n");
}

return 0;

I have also tried doing this

int num,value;
scanf("%d", &num);

for(int i=1; i<=num; i++){
    for(int j = i; j < i+num; j++){
        value = i;
        if(value < j){
            value+=1;
        }
        printf("%d ", value);
    }

    printf("\n");
}

return 0;

However, I got this as a result

   1 2 2 2 2 2

   2 3 3 3 3 3

   3 4 4 4 4 4

   4 5 5 5 5 5

>Solution :

I didn’t understand how you are getting those two extra columns, but to get the last column as 1 incremented you can simply use this.

for(int i=1; i<=num; i++){
    for(int j = i; j < i+num; j++){
        if(j==(i+num)-1)
            printf("%d ",i+1);
        else
            printf("%d ", i);
    }

    printf("\n");
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading