0
#include <bits/stdc++.h>
using namespace std;
//program to find index of number giving sum as m
int main() {
    int m;
    cin>>m;    //sum
    int n;         //size of array
    cin>>n;
    int a[n];
    for(int i=1; i<=n; i++) {
        cin>>a[i];
    }
    int k=1;
    while(k<=n) {
        for(int i=1; i<=n; i++)
        {
            if(a[k] + a[k+i]==m) {
                cout<<k<<" "<<k+i<<"\n";    //printing index of numbers giving sum as m
                break;
            }
        }
        k++;
        
    }
    return 0;
}

/* i/p 4 4 2 2 4 3 */

/* o/p 1 2 3 7 */

why i am getting 3 7 as output even if i am using break statement /*i/p 4 4 2 2 4 3 / / o/p 1 2 3 7 */

  • 1
    You have multiple problems... It starts with you using [variable-length arrays](https://en.wikipedia.org/wiki/Variable-length_array), which are not part of the C++ language. Then you continue to use one-based indexing, arrays in C++ are zero-based. And you then go out of bounds of the array you created. – Some programmer dude Aug 27 '20 at 11:01
  • 1
    `int a[n];` is not C++. Did you try to debug your code? – Quimby Aug 27 '20 at 11:01
  • 1
    @Someprogrammerdude TBF, g++ does have support for VLA:s – klutt Aug 27 '20 at 11:03
  • It seems like you would need a good book about C++. This is now how you write C++ code – klutt Aug 27 '20 at 11:15
  • Oh, and [don't include ``](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h). And [`using namespace std;` is a bad habit as well](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice). It seems you use a so-called "competition" site to learn how to use C++, and they're really bad as tutors and learning resources (unless all you want to learn are bad habits and bad code). Get [a few good books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282) or take classes. – Some programmer dude Aug 27 '20 at 11:30

1 Answers1

0

In C++ array indexes start at zero not one, so

for(int i=0; i<n; i++) {
    cin>>a[i];
}

Similarly here, but also because you access the array at index k+1 you need to compare this against n rather than k.

int k=0;
while(k+1<n) {
    for(int i=0; i<n; i++)
    {
        if(a[k] + a[k+i]==m) {
            cout<<k<<" "<<k+i<<"\n";    //printing index of numbers giving sum as m
            break;
        }
    }
    k++;
    
}

Any array accesses that are out of bounds give your whole program undefined behaviour meaning anything is possible when you run the program.

Plus you are using variable length arrays int a[n]; which are not legal C++. In C++ array bounds must be compile time constants.

john
  • 71,156
  • 4
  • 49
  • 68
  • There is also an out of band access here: `a[k+i] `. Better to use `a[i]` and start `i` at `k+1` – Damien Aug 27 '20 at 14:18