Home > Back-end >  What could be wrong in my C code for finding nth term in AP?
What could be wrong in my C code for finding nth term in AP?

Time:09-18

   class Solution {
 public:
   int nthTermOfAP(int A1, int A2, int N) {
  int d=A2-A1;
  int current=A1;
  int arr[10];
  
  for (int i=0;i<N;i  )
  {
     arr[i]=current;
     current d;
  }
  cout<<arr[N-1];
}
};
// { Driver Code Starts.
int main() {
   int t;
   cin >> t;
   while (t--) {
       int A1, A2, N;
       cin >> A1 >> A2 >> N;
       Solution ob;
       cout << ob.nthTermOfAP(A1, A2, N) << "\n";
   }
}
 // } Driver Code Ends  

i am getting output as 26295968. Please explain why i am getting such a large number? do i have to intialize any number to 0?

CodePudding user response:

Your nthTermOfAP function doesn't return any value. So when you try to cout the function that doesn't return any value, its gonna give you an output like 26295968.

So you can either do two things:

  1. Add a return value in your nthTermOfAP function.
  2. Simply remove the cout from cout << ob.nthTermOfAP(A1, A2, N) << "\n"; in your int main(). And make the function datatype into void instead of int. With void you are not expected to give a return value.

CodePudding user response:

The return type of your function should be void instead of int. Then you can remove the cout command. Instead of current d; You should use current = current d;

    for (int i=0;i<N;i  )
    {
       arr[i]=current;
       current = current d;
    }
    cout<<arr[N-1];

Also you can used the equation nth term of an Ap= a (n-1)*d

  • Related