convert for loop into while and do..while

Light Poster
12Dec2007,19:21   #1
philay's Avatar
Code:
#include<stdio.h>
int main ()
{
int i,j;

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

return 0;

}
The output is
1
22
333
4444
55555

this is the "for" method, how do i convert it into while and do..while format? i just still noob in programming , any expert help me out pls? thx

Last edited by shabbir; 12Dec2007 at 22:22.. Reason: Code block
Ambitious contributor
12Dec2007,19:36   #2
Salem's Avatar
for ( a ; b ; c ) d;

Is approximately
a;
while ( b ) { d; c; }
Light Poster
12Dec2007,19:51   #3
philay's Avatar
ya, but if got 2 loops? for(i=0;i<=8;i++) the first loop then inside another for (j=0;j<=i;j++)?
Ambitious contributor
12Dec2007,22:12   #4
Salem's Avatar
So two for loops become two while loops - what's the problem?
Light Poster
13Dec2007,06:25   #5
philay's Avatar
Code:
int i=1,j=1;

while(i<=5)  {
    printf("%i",i);
    i++;
    while(j<=i)  {
       printf("\n");
       j++;
}
but if i write like this, i compile cant get the correct output same as the for loop
1
22
333
4444
55555
Light Poster
13Dec2007,06:28   #6
philay's Avatar
Code:
int i=1,j=1;

do {
   printf("%i",i);
   i++;
do {
   printf("\n");
   j++;
}while(j<=i);
}while(i<=5);
Go4Expert Founder
13Dec2007,08:18   #7
shabbir's Avatar
For while loop you should increment the counter as the last statement and then it will be equivalent.

Do while loops are a bit different and cannot be equal to for loop but in your case applying the increment as the last statement of the loop would do.
Light Poster
13Dec2007,10:14   #8
philay's Avatar
i don't really get what u really mean.. how about u post the code for me? then i will know better
Ambitious contributor
13Dec2007,12:36   #9
Salem's Avatar
Refer to my other post
Code:
for(i=1;i<=5;i++)  {
  for(j=1;j<=i;j++)
    printf("%i",i);
  printf("\n");
}
Becomes
Code:
i=1;
while ( i<=5 ) {
  for(j=1;j<=i;j++)
    printf("%i",i);
  printf("\n");
  i++;
}
Now apply the same transformation to the inner loop, and you're done.
Light Poster
13Dec2007,14:19   #10
philay's Avatar
kk, thx so much for the help