Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is wrong with the loops

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?

like image 740
Tapasweni Pathak Avatar asked Feb 22 '26 12:02

Tapasweni Pathak


1 Answers

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.

like image 100
Petar Minchev Avatar answered Feb 25 '26 00:02

Petar Minchev