Reputation: 562
I am solving a problem of adding the last digits of numbers lying between a range (for ex. between 'm' and 'n' where m < n).I have coded this
#include <stdio.h>
int main()
{
int t=0;
long int m=0,n=0,num=0,sum=0,lsum=0,i=0;
scanf("%d",&t);
while(t--){
scanf("%ld%ld",&m,&n);
i=m;
while(i<=n){
while(i!=0){
num=i%10;
i/=10;
}
lsum=lsum+(sum%10);
i++;
}
}
printf("\n%ld",lsum);
return 0;
}
Here t=No of Test Cases. m and n is the range. I don't know why it is running infinitely in the terminal. I am using gcc(4.3.2) compiler.How can I optimize it for speed ,or is it the case where the while conditions are never terminated, but why?
Upvotes: 3
Views: 166
Reputation: 979
There is an infinite loop int the code :
while(i<=n)
{
while(i!=0)
{
num=i%10;
i/=10;
}
lsum=lsum+(sum%10);
i++;
}
the first while(1<= n) is always true : the second loop makes i = 0 or i = 1 !
Upvotes: 4
Reputation: 47363
You are dividing the i
: i/=10
. This means that i
is always set back to 1
at the end of the loop. You should use a temporary variable for the dividing.
Like this:
while(i<=n){
int temp = i;
while(temp !=0){
num=temp %10;
temp /=10;
}
lsum=lsum+(sum%10);
i++;
}
P.S. There are many other errors in your code. But they are not connected with the infinite looping.
Upvotes: 4