Saturday, 9 April 2016

TEST-Life, the Universe and Everything


Online with my first ever post, dont expect my blog to be all glittery and stuff. It is not gonna look good, for a while. So if the content or the topic interests you, please leave a comment.

Apparently, Im only going to try to solve classical problems in my initial few posts, I dont know why. 

So let us start with the first problem http://www.spoj.com/problems/TEST/

--------------------------------------------------------------------------------------------------------------------------

Basic understanding says run a loop for input, stop taking the input when input is 42 and then print the output as it is except 42.

BUT, the sample input shows a user entered 99 after 42, so are we not supposed to stop taking the inputs after getting 42?? Ofcourse the question never says anything about when to stop taking inputs.

The time limit is 10s. We can simply make an array with INT_MAX holding capacity(what is the right term?) and we will stop taking inputs as soon as user enters 42 and to match the input of the Example provided, I will be using do while..so lets see, Honestly, I don't know if a[INT_MAX] will work as an array. But we all are learners here and a mistake never hurts.

 First Attempt:-
#include <stdio.h>
#include <stdlib.h>  ---->INT_MAX is part of this header

int main()
{
int a[INT_MAX],c=0,d=0;
do
    {
     scanf("%d",&a[c]); //taking inputs
     c++;    
     }
while(a[c]!=42); //breaking at input=42.
while(d<c)
   {
    printf("%d\n",a[d]); //printing the remaining values.
    d++;
    }
return 0;
}
Apparently, putting a[INT_MAX] gives compilation error. But even after declaring a[100] or a[1000], compiler was giving me a runtime error. What is wrong with the above program??

A very small mistake which I made was with the "DO" portion. Suppose, the user inputs value 36 and it is stored in a[3],suppose. We then do c++ ,and the while checks whether a[4]= 42 or not. Which means,practically,this is an infinite loop. To fix this, we can write while(a[c-1]!=42) . There are a lot of different solutions anyways from hereon.

FIXED SOLUTION:-
#include <stdio.h>

int main()
{
int a[1000],c=-1,d=0;
do
    {
     c++;
     scanf("%d",&a[c]);
   
     }
while(a[c]!=42);
while(d<c)
   {
    printf("%d\n",a[d]);
    d++;
    }
return 0;
}

I do understand that this was one easy problem but upcoming problems will be a bit tricky, hope so. Please leave comments or complains.

No comments:

Post a Comment