-
for loop program in c
Code:
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,k=1,l;
clrscr();
for(i=1;i<=4;i++)
{
for(j=4-i;j>0;j--);
printf(" ");
for(l=1;l<=i;l++)
{
printf("%d ",k);
k++;
}
printf("\n");
}
getch();
}
/*This is the program i wrote to get the folloeing output:
1
2 3
4 5 6
7 8 9 10
instead it generating
1
2 3
4 5 6
7 8 9 10
can anyone tell me where the logic is wrong?
i am using turbo c compiler.
plz help me soon.
thanks.*/
-
Using Turbo C is the first mistake. Upgrade to something from this millennium, like Pelles C or Code::Blocks using MinGW.
The correct form is int main(void), and you need to return an integer at the end, usually 0.
As for your logic problem, I see no difference between your expected and actual output, so I think your program is working fine.
-
@panks, if you need to show letters or digits in a certain shape on the forum, put them in code tags.
Otherwise the forum software scrunches it all to far left side, and removes extra spaces also.
-
thanks for your support.
sorry...
Code:
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,k=1,l;
clrscr();
for(i=1;i<=4;i++)
{
for(j=4-i;j>0;j--);
printf(" ");
for(l=1;l<=i;l++)
{
printf("%d ",k);
k++;
}
printf("\n");
}
getch();
}
/*This is the program i wrote to get the folloeing output:
1
2 3
4 5 6
7 8 9 10
instead it generating
1
2 3
4 5 6
7 8 9 10
can anyone tell me where the logic is wrong?
i am using turbo c compiler.
plz help me soon.
thanks.*/
-
Look at the figure you want to draw:
Code:
1
2 3
4 5 6
7 8 9 10
The base row is 7 char's wide, if you ignore the zero on the end of the 10. The number of rows is 4, so we first need to find the center point of the base, so we can place the 1 correctly, right in the center:
center point = cpoint = (base/2) +1 for the 0 on the 10 = 4
Now things start to shape up:
Code:
cp=4; //the center point
for(rows = 0,n=0; rows < 4; rows++) { //for each row
for(cols = 1; cols <= 8; cols++) { //for each column of a row
if cols less than cp-rows
printf(" ");
if cols equals cp-rows
for i equals 0; i less than or equal to rows; i++
printf("%d ",++n);
}//end of inner for loop
print newline;
}
You need to translate the pseudo code statements into C code.
-
Please fix your definition of main (see my first post for explanation/correct form).
So you already have a loop that should print out the correct number of spaces before the top row, but there's a small problem:
Code:
for(j=4-i;j>0;j--);
printf(" ");
Drop that semicolon, It's preventing you from running that printf in a loop, so you're only printing one space before each row.