Counting terms in Collatz sequences until 1 is reached or a limit is exceeded
Overflow Bug

The reason your program is timing out is because your variable val is defined as an int instead of a long long.  Because of this, val can become negative during the line val=(val*3) + 1, which leads to an infinite loop.  You should change the type of val to long long.  If you want to test the infinite loop yourself, try this test case and see what happens:

113383 2147483647


Output Bug

Your program has two output related errors:


You should initialize n=1 instead of n=0.
Your code is missing the line n++.


The above two problems mean that your program is outputting something like:

Case 0: A = 100, limit = 100000, number of terms = 25
Case 0: A = 101, limit = 100000, number of terms = 25


instead of the correct format of:

Case 1: A = 100, limit = 100000, number of terms = 25
Case 2: A = 101, limit = 100000, number of terms = 25