-1
#include<bits/stdc++.h>
using namespace std;

int check(){
    int p,q;
    int count=0;
    cin>>p>>q;
    if(q-p>=2){
        count++;
    }
    cout<<count;

}

int main(){
    int n;
    cin>>n;
    for(int i=0;i<n;i++){
        check();
    }
}

How to carry forward the value of 'count' in multiple iterations of for loop. Everytime the loop reiterates the 'count' value sets to '0' again but I want it to store values from previous iterations. Since the loop reiterates 'n' but everytime the loop enters, the value of count sets back to 0.

Is there something I can do with the initialization of count (count=0) ??

  • 1
    Sounds like you need to make `count` a function parameter, then you can control what its value will be each time you call `check` in your for loop. – NathanOliver Feb 15 '23 at 16:15
  • 5
    `p`, `q` and `count` are all function local objects. They are created when you enter the function and destroyed when you leave the function. Use `static int count = 0;` to indicate that you want only a single `count` to be shared among all calls to `check`. – François Andrieux Feb 15 '23 at 16:16
  • 3
    Where did you learn `#include`? Never go there again. Block that website in your browser. – Eljay Feb 15 '23 at 16:16
  • 2
    `#include` -- Do not use this header file. All your program requires is `#include ` – PaulMcKenzie Feb 15 '23 at 16:17
  • [Why should I not `#include `?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) – Evg Feb 15 '23 at 16:20

1 Answers1

0

Every time you enter the function check, you initialize the local variable count to zero. Since you need to keep track of the total number of items that satisfy your condition, you should either place it as global variable or, more correctly, initializing the variable inside the caller function and pass it to the callee as a reference.

Here is the code with the second solution, without the #include<bits/stdc++.h> directive (which is not suggested).

#include <iostream>

int check(int& count){
    int p,q;
    std::cin>>p>>q;
    if(q-p>=2){
        count++;
    }
    std::cout<<count;
}

int main(){
    int count = 0;
    int n;
    std::cin>>n;
    for(int i=0;i<n;i++){
        check(count);
    }
}
GURU
  • 16
  • 1
  • 2
  • 1
    Alternatively, you can have `check()` return its own local count when called, and have the loop increment a separate `count` in `main()`, eg: `int check(){ int count = 0; ... ++count; ... return count; } int main(){ int count = 0; ... count += check(); ... }` – Remy Lebeau Feb 15 '23 at 20:12