[C++] Am I using for loops correctly?

help
c-plus-plus
easy
question

#1

My solution for CLEANUP goes as follows:

#include <iostream>
#include <set>
#include <vector>
#define lo unsigned long long
using namespace std;
void solve(lo M, lo N,lo a[]){
    set<lo> s;
    vector<lo> v;
    vector<lo> j;
    vector<lo> k;
    bool polar = true;
    //creates list of 1,2..M
    for (lo x  = 1; x<=M;x++){
        s.insert(x);
    }
    //deletes terms
    for (lo x  = 0; x<N;x++){
        s.erase(a[x]);
    }
    for (auto x : s) {
        v.push_back(x);
    }
    for (lo x = 0; x<v.size();x+=2){
            j.push_back(v[x]);
    }
    for (lo x = 1; x<v.size();x+=2){
        k.push_back(v[x]);

    }
    for (auto x : j) {
        cout << x << " ";
    }
    cout << endl;
    for (auto x : k) {
        cout << x << " ";
    }
    cout << endl;

}
int main() {
    //freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);

    lo T;
    cin >> T;
    lo M,N = 0;
    lo a[N];
    for (lo x = 0; x<T;x++){
        cin >> M >> N;
        for (lo y = 0; y<N;y++){
            cin >> a[y];
        }
        solve(M,N,a);
    }

    return 0;
}

However I seem to be getting wrong answers. I suspect this is because of how I used for loops. I tried to use increments of 2, however I’m not sure if that causes overflow or not(goes past the set limit). Can anyone confirm? Thanks


#2

hey everything is correct but you are doing a small mistake.

Initially N is 0 and you are declaring an array a[N] then you can store only one element in the array.

Declare array after scaning the value of N then you will get AC.I just changed that got AC.here is the link


#3

Another thing I want to add with @hruday, it’s always good practice to declare an array globally. There’s always chance of stack overflow if you declare an array locally.


#4

The best way to understand loops is to understand the concept behind them. Loops are used in programming when you need to perform a task more than once. While loops and For loops exist to this end. the main difference in the two, besides the code you use to write them, is that while loops check the condition at the end of the loop, and Do My Essays will repeat the loop until the while condition is met.


#5

ty so much, this explains why my last 3 solutions have been wrong lol