Page 1 of 212> Show 40 post(s) from this thread on one page

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   convert for loop into while and do..while (http://www.go4expert.com/forums/convert-loop-dowhile-t7815/)

 philay 12Dec2007 19:21

convert for loop into while and do..while

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

 Salem 12Dec2007 19:36

Re: convert for loop into while and do..while

for ( a ; b ; c ) d;

Is approximately
a;
while ( b ) { d; c; }

 philay 12Dec2007 19:51

Re: convert for loop into while and do..while

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 12Dec2007 22:12

Re: convert for loop into while and do..while

So two for loops become two while loops - what's the problem?

 philay 13Dec2007 06:25

Re: convert for loop into while and do..while

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 13Dec2007 06:28

Re: convert for loop into while and do..while

Code:

```int i=1,j=1; do {   printf("%i",i);   i++; do {   printf("\n");   j++; }while(j<=i); }while(i<=5);```

 shabbir 13Dec2007 08:18

Re: convert for loop into while and do..while

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 13Dec2007 10:14

Re: convert for loop into while and do..while

i don't really get what u really mean.. how about u post the code for me? then i will know better

 Salem 13Dec2007 12:36

Re: convert for loop into while and do..while

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 13Dec2007 14:19

Re: convert for loop into while and do..while

kk, thx so much for the help

 All times are GMT +5.5. The time now is 08:01. Page 1 of 212> Show 40 post(s) from this thread on one page