-4
#include <iostream>
using namespace std;


int compute_binare_code(int n, int a[][4]){
    int i,j;
    int bC = 0, p = 1;
    for(i = 1;i <= n;i++){
        for(j = i+1;j <= n;j++){ //just counting bC
            bC += a[i][j]*p;
            p =p*2;
           } 
     }
    return bC;
}

int main(){
  cout << "mata3";
  int a[4][4],b[5][5],i,j;
  for(i=1;i<=4;i++)
    for(j=1;j<=4;j++)
        if( (i+j)%2 == 0)
            a[i][j]=0;
        else
            a[i][j]=1;


  cout<<"mata1";
  cout<<compute_binare_code(4, a);
  cout<<"mata2";
  return 0;
}

When i run this program, it doesn't give any error but it runs in background forever. It does not print anything, not even "mata3". Can someone explain me why?

Nirod
  • 25
  • 5
  • Welcome to Stack Overflow. Please take the time to read [The Tour](http://stackoverflow.com/tour) and refer to the material from the [Help Center](http://stackoverflow.com/help/asking) what and how you can ask here. – πάντα ῥεῖ Jun 08 '17 at 19:20
  • 4
    Array indexes go from zero to size-1. So for an array of four elements, the valid indexes are from `0` to `3` (inclusive). If you use index `4` then you are *out of bounds* and have *undefined behavior*. – Some programmer dude Jun 08 '17 at 19:20
  • 1
    The right tool to solve such problems is your debugger. You should step through your code line-by-line *before* asking on Stack Overflow. For more help, please read [How to debug small programs (by Eric Lippert)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). At a minimum, you should [edit] your question to include a [Minimal, Complete, and Verifiable](http://stackoverflow.com/help/mcve) example that reproduces your problem, along with the observations you made in the debugger. – πάντα ῥεῖ Jun 08 '17 at 19:20
  • thanks Some programmer dude :). – Nirod Jun 08 '17 at 19:22
  • 1
    Also, `cout` is row buffered. Try adding a newline in each print statement and it should appear immediately. Or flush it. – Klas Lindbäck Jun 08 '17 at 19:22
  • any reason to do this ***for(i=1;i<=4;i++)*** instead of ***for(i=0;i<4;i++)***??? – ΦXocę 웃 Пepeúpa ツ Jun 08 '17 at 19:23
  • 3 years ago, on paper, it worked.but seems that on computer it doesn`t work :)) – Nirod Jun 08 '17 at 19:27

1 Answers1

0

Arrays in C++ are indexed from 0.

Your for loop increments i/j from 1 to 4, but it should be 0 to 3.

See also Accessing an array out of bounds gives no error, why?