this is the program i need to convert while loop statement into for loop statement. I already tried my best, but it does not work. Please help me. Thanks
#include %26lt;stdio.h%26gt;
#include %26lt;conio.h%26gt;
#define true 1
#define false 0
main()
{
clrscr();
int arr[5],a;
int location=0;
int const max=5;
printf("\nEnter 5 Numbers:\n");
for(a=0;a%26lt;max;a++)
{
printf("\nArray[%d]\t",a);
scanf("%d",%26amp;arr[a]);
}
int key=0,low=0,high=0,mid=0;
printf("\nEnter the value we need to look for:\n");
scanf("\n%d",%26amp;key);
low=0,high=max,mid=(low+high)/2;
int found=false;
while((low%26lt;=high)%26amp;%26amp;(!found))
{
if(key%26gt;arr[mid])
low=mid+1;
else
if(key%26lt;arr[mid])
high=mid+1;
else
{
found=true;
location=mid;
}
mid=(low+high)/2;
}
if(found)
{
printf("\nThe value was found in \n");
printf("\nArray[%d]\t",location);
}
else
{
printf("\nThe value was not found\n");
}
getch();
return(0);
}
How can i convert while loop statement of the Turbo C program below in "for loop statement"?
just change foll lines to
while((low%26lt;=high)%26amp;%26amp;(!found))
{
//**********************************
this -----
//*****************************
for(;low %26lt;=high;)
if(found) break;
{
Reply:Well, that doesn't look like it's well suited for a for loop, but here's what I would do:
Change:
while((low%26lt;=high)%26amp;%26amp;(!found))
{
if(key%26gt;arr[mid])
low=mid+1;
else
if(key%26lt;arr[mid])
high=mid+1;
else
{
found=true;
location=mid;
}
mid=(low+high)/2;
}
To:
for (
low=0;
(low%26lt;=high)%26amp;%26amp;(!found);
(key%26gt;arr[mid])?
low=mid+1:high=mid+1)
{
if(key==arr[mid])
{
found=true;
location=mid;
}
mid=(low+high)/2;
}
(Sorry about the random line breaks, Yahoo puts in stupid elipsis.)
Or maybe just to:
for (;(low%26lt;=high)%26amp;%26amp;(!found);)
{
if(key%26gt;arr[mid])
low=mid+1;
else
if(key%26lt;arr[mid])
high=mid+1;
else
{
found=true;
location=mid;
}
mid=(low+high)/2;
}
But that last one is sort of just cheating. :P Like I said, this doesn't seem like something that could benefit from a for loop...
survey monkey
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment