Why is it giving wrong count
In this question we have to find out how many elements are greater than the next element of an array
#include
using namespace std;
int main() {
//number of testcases
int t;
cin>>t;
while(t--){
//taking number of elements in an array
int n,count;
cin>>n;
//taking array
int a[n];
count=0;
for(int i=1;i<=n;i ){
cin>>a[n];
}
//checking array
for(int j=1;j<=n-1;j ){
if(a[j]>a[j 1])
{
count ;
}
}
cout<<count<<endl;
}
return 0;
}
Input 5 1 2 3 4 1 Expected Output 1 Output through above code 2
CodePudding user response:
There are several problems with your code:
Problem 1
You're going out of bounds of the array a
which leads to undefined behavior, when you wrote
cin >> a[n]; //undefined behavior
Note that indexing of arrays starts from 0
instead of 1
in C .
Problem 2
In standard C , the size of an array must be a compile-time constant. This mean the following is incorrect in your code:
int n;
cin>>n;
int a[n]; //NOT STANDARD C BECAUSE n IS NOT A CONSTANT EXPRESSION
Better would be to use std::vector
instead of built in array.
int n = 0;
std::cin >> n;
std::vector<int> a(n); //this creates a vector of size n
//take input from user
for(int& element: a)
{
std::cin >> element;
}
int count = 0;
for(int i = 0; i< n - 1; i)
{
if(a[i] > a[i 1])
{
count;
}
}