Consider the follow C code int result 1 for unsigned int i

Consider the follow C code: int result = 1; for (unsigned int i = 100; i >= 0; --i) { result *= i; } Why will this code loop indefinitely and how would you fix this issue?

Solution

  int result =1;

          for (unsigned int i=100;i>=0;--i)

          {

                    result =result * i;

          }

Solution : the reason behind this is that here i is an unsigned int , first time when loop started the value of i is 100 after checking condition (i>=0) if the condition will be true it decrement the value of i then performs the operation but this process will continue till i!=0 . Lets understand what happen when i will be 0(i=0), according to condition loop should be terminated but it goes into infinite because i is unsigned bit when the ith value is zero it will circle back to the maximum possible value of an unsigned integer, this process will continue when i will be reached at 0.

Solution of this problem is :

#include<stdio.h>

#include<conio.h>

long result =1;

int main()

{

          static double result =1;

          for(unsigned int i=100;i>0;--i)// iterate this loop from 100 to 1

          {

          printf(\"\\t %d\",i);

          result =result * i;

          }

          printf(\"\ \");

          printf(\"\ The Result is :%ld\",result);

          return 0;

}

 Consider the follow C code: int result = 1; for (unsigned int i = 100; i >= 0; --i) { result *= i; } Why will this code loop indefinitely and how would you

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site