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
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
CodePudding user response:
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");
}
CodePudding user response:
Here is what I did. I am not doing the updation of i in the first for loop. Rather I am checking if I have reached the last column in the second for loop then update i to i .
#include <stdio.h>
int main(){
int num, value;
scanf("%d", &num);
for (int i=1; i<num; ) {
for (int j=i; j<(num i); j ) {
if (j == (num i-1)) {
i ;
printf("%d", i);
break;
}
printf("%d", i);
}
printf("\n");
}
return 0;
}