Ok here's a program of turbo c.The output of this program is RESULT=95.
The question is how?I just can't get it.
#include%26lt;stdio.h%26gt;
#include%26lt;conio.h%26gt;
int change(int[]);
main()
{
int a,arr[8]={5,19,25,6,35,8,45,50};
a=change(arr);
printf("RESULT=%d",a);
getch();
}
int change(int a[])
{
int limit=0,i=0,sum=0;
while(!limit)
{
sum+=a[i];
if(sum%26gt;90)
limit++;
}
return(sum);
}
TURBO C question?
You get 95 because your integer 'i' is equal to zero.
a[i] = a[0] = 5
a[0] is 5 because 0 is the first index value in the array which you have set to 5 here: 'int a,arr[8]={5,19,25,6,35,8,45,50..'
while (!limit) //while limit is equal to zero
{
sum +=a[i] // 'i' is 0 and is never changed
if(sum%26gt;90) // if sum is greater than ninety --%26gt;
limit++; // then add 1 to limit
}
What I am trying to show you is that as long as 'limit' is zero, you are going to continue to add 5 to 'sum'. In your if statement, limit++ will add 1 to 'limit' and effectively end the while loop. The problem is, 'limit++' will not be executed until 'sum' is greater than (not equal to) 90. So you will keep adding 5 to 'sum' until it is greater than 90 and the highest value you can get greater than 90 by adding fives is 95. No other number than 5 is added to 'sum' because the value of 'i' never changes and always calls the same index in your array.
If you are looking to loop through the array, your code should look like this:
#include%26lt;stdio.h%26gt;
#include%26lt;conio.h%26gt;
int change(int[]);
main()
{
int a,arr[8]={5,19,25,6,35,8,45,50...
a=change(arr);
printf("RESULT=%d",a);
getch();
}
int change(int a[])
{
int limit=0,i=0,sum=0;
while(!limit)
{
if (i%26lt;8) // this prevents you from loading indexes that aren't there
{
sum+=a[i];
i++; //this adds one to 'i' each time you loop
}
else
{
limit++; //just in case all of the values don't add up to 90
}
if(sum%26gt;90)
limit++;
}
return(sum);
}
Reply:98 should be the correct answer if you have the line as:
sum += a[i++]
to increment i each time.
As it reads, i=0 always, so each time you add 5 until the sum is greater than 90.
Reply:I forget c, but remember c++....try using dry run, that is use a paper and a pencil and compile the prog. u sud be getting confused in the function part this might help-
first the main gets executed, then in a=change(arr) function change gets called and gets executed by the compiler....here the answer 95 gets calculated and gets stored in sum, this value of sum gets returned to the main function which, which prints its value
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment