Help with recursive multiplication table

closed account (y0q21hU5)
Hey there. I am a beginning c++ programmer and had a few questions on a program i wrote.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
int mult(int n, int a, int b, int tab[5][5]){
	if( a == 0 && b <= n) {
		tab[a][b] = b;
		std::cout<< tab[a][b];
		return mult(n, a, b+1, tab);
	}
	else if( b == 0){
		tab[a][b] = a;
		std::cout << tab[a][b];
		return mult(n, a, b + 1, tab);
	}
	
	 else if(b <= n){
		tab[a][b] = a * b;
		std::cout<<tab[a][b];
		return mult(n, a, b + 1, tab);
	}
	else if (a <= n){
		b = 0;
		std::cout <<std::endl;
		return mult(n, a+1, b, tab );
	}
	else{
	return 0;
	}
		
}

int main(){
	unsigned int n = 5;
	int a =0, b = 0;
	int tab[5][5] = {};
	mult(n, a, b, tab);
}

The code complies and runs as it should but at the end it will tell me segmentation fault. I was wondering why. Also, how could I set the array to a user entered size? Thanks.
On lines 3, 14, and 19, you accidentally used <= n instead of < n.

For arrays of user-defined size, I recommend you look into std::vector. You will want a vector of vectors.
closed account (y0q21hU5)
thanks! that worked perfectly. do you know of anyway to do it other than using vectors? My teacher is really picky on what we use and we can not use std::vector or std::string.
If you are required to do it the deprecated way, you can do it like this:
1
2
3
4
5
6
7
unsigned xsize, ysize;
std::cin >> xsize >> ysize;
int **tab = new int*[xsize];
for(unsigned i = 0; i < xsize; ++i)
{
    tab[i] = new int[ysize];
}
1
2
3
4
int mult(int n, int a, int b, int **tab)
{
    //...
}
closed account (y0q21hU5)
Thanks!
Topic archived. No new replies allowed.