Hackerrank Modular Range Queries
Can this code be optimized in any way?


Some of the obvious points:

Remove unnecessary #include statements

Your code doesn't use any stuff from these headers

#include &lt;cmath&gt;
#include &lt;cstdio&gt;
#include &lt;vector&gt;
#include &lt;algorithm&gt;


So you can remove them.

Don't use using namespace std;

That's generally considered bad practice.

Rather use 

using std::cout;
using std::cin;


if you want to avoid typing these out.

Use meaningful variable names

Variable names like 

int n,q;
int A[n];


don't tell anything about their semantics.

Standard C++ doesn't support VLA's

Code like 

int A[n];


isn't portable. Variable Length Arrays aren't supported by the current c++ standard.

Use

std::vector A(n);


instead to create a dynamically sized array.

Check for successful and valid input

cin&gt;&gt;a&gt;&gt;b&gt;&gt;x&gt;&gt;y;


You never check if the above statement succeeded before proceeding to apply the algorithm.

Better do something like

if(!(cin&gt;&gt;a&gt;&gt;b&gt;&gt;x&gt;&gt;y)) {
    std::cout &lt;&lt; "Bad input encountered!" &lt;&lt; std::endl;
    return 1;
}


Since 

t%x


may segfault when x is zero, you should at east have an assert:

std::assert(x);
if(t%x==y) { // ...
}


Always use braces for scoped blocks

for(int i=0;i&lt;n;i++)
    cin&gt;&gt;A[i];


should be

for(int i=0;i&lt;n;i++) { // &lt;&lt;&lt;&lt;&lt;&lt;&lt;
    cin&gt;&gt;A[i];
} // &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;


Missing the braces makes that code error prone for changes. It's always better to  clarify the scope with conditional or loop statements.

Use prefix incrment (decrement) if you don't need to preserve the previous value

Instead of 

for(int i=a;i&lt;=b;i++)
c++;


use

for(int i=a;i&lt;=b;++i)
++c;


You obviously don't need the old value preserved by the postfix increment operations.



Performance of formatted text extraction


  The values of of n,q,a,x,y,b are ranging from 1 to 40000. so it gets the timeout therefore it needs to further optimised


As for your performance concerns:

Formatted text extraction in c++ is costly. You may get a performance improvement just using scanf() in this case.

While

cin&gt;&gt;a&gt;&gt;b&gt;&gt;x&gt;&gt;y;


applies four function calls

scanf("%d %d %d %d",a,b,x,y);


would be only one call. Also the internal implementation of the formatted text extraction syntax boils down to some scanf() like functions for most of the c++ compilers anyways.