convert for loop into while and do..while

philay's Avatar, Join Date: Dec 2007
Light Poster
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
Salem's Avatar, Join Date: Nov 2007
Ambitious contributor
for ( a ; b ; c ) d;

Is approximately
a;
while ( b ) { d; c; }
philay's Avatar, Join Date: Dec 2007
Light Poster
ya, but if got 2 loops? for(i=0;i<=8;i++) the first loop then inside another for (j=0;j<=i;j++)?
Salem's Avatar, Join Date: Nov 2007
Ambitious contributor
So two for loops become two while loops - what's the problem?
philay's Avatar, Join Date: Dec 2007
Light Poster
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
philay's Avatar, Join Date: Dec 2007
Light Poster
Code:
int i=1,j=1;

do {
   printf("%i",i);
   i++;
do {
   printf("\n");
   j++;
}while(j<=i);
}while(i<=5);
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
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.
philay's Avatar, Join Date: Dec 2007
Light Poster
i don't really get what u really mean.. how about u post the code for me? then i will know better
Salem's Avatar, Join Date: Nov 2007
Ambitious contributor
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.
philay's Avatar, Join Date: Dec 2007
Light Poster
kk, thx so much for the help