Krejw February 2016

Convert a `while` loop to a `for` loop

I'm new in C, and not sure if my loop is correctly converted.

while(a<b--)
{
    do
    {
        d+=a++;
    }
    while(a!=c);
    c+=a&b;
 }

and it's my loop

for( ; a<b ; b--)
{
    d += a++;
    for( ; a != c ; a++)
    {
        c+= a&b
    }   
}

I know it's maybe easy and stupid, but I hope you'll help me :) Thx

Answers


Hemant Kumar February 2016

I think it should be something like this :

for(;a<b--;){ 
for(d += a++ ; a != c ; )
{
  d += a++; 
}    
c+= a&b
}

The above logic works !

I ran both programs as below and they output the same result :

Program1:[derived from your program 1]

#include<stdio.h>
int main(){

int a=10,b=10,c=10,d=10;

while(a<b--)
{
do
{
    d+=a++;
}
while(a!=c);
c+=a&b;
}
printf("a=%d\tb=%d\tc=%d\td=%d",a,b,c,d);
}

And it outputs this :

a=10    b=9 c=10    d=10

Similarly the changed Program2 :[As requested]

#include<stdio.h>
int main(){

int a=10,b=10,c=10,d=10;

for(;a<b--;){
for(d += a++ ; a != c ; )
{
d += a++;
}
c+= a&b;
}
printf("a=%d\tb=%d\tc=%d\td=%d",a,b,c,d);
}

And it outputs the same :

a=10    b=9 c=10    d=10

Post Status

Asked in February 2016
Viewed 3,819 times
Voted 6
Answered 1 times

Search




Leave an answer