Pointer, Recursion, Delete...

Using C++, define an integer pointer in main(), and use this pointer to dynamically allocate an integer array with 100 elements; assign the array with random numbers in range [0, 999]. Then pass the array as parameter(s) to a recursive function fun() which counts the number of the integers that are even multiple of three, and prints those integers; after the function call, print the "counter" result; finally, remember to use delete to deallocate the array memories. Please tell me why my code isn't working.

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
36
37
38
39
//COMP 1224- Sec.2
//Lab #3 April 2015

#include <iostream>
using namespace std;

int main()
{
	int counter = 0;
	int *p;
	p = new int [5];
	int a = rand ()% 999;

	for (int i=0; i<100; i++)
	{
		p[i]=a;
		a = rand ()% 999;
	}

	for (int i=0; i<100; i++)
	{
		cout << "[" << i << "] = " << p [i] << endl;
	}

	for (int i = 0; i<100; i++)
	{
		if ((p[i] % 3 == 0) && (p[i] % 2 == 0))
		{
			counter++;
		}
	}

	cout << "The Number of Even Multiples of three Is" << counter << endl;

	delete[] p;

	system("PAUSE");
	return 0;
}
p = new int [5];

^You were supposed to allocate an array of 100 elements, not 5 elements.

for (int i=0; i<100; i++)

^This would lead to a segfault, because you are trying to access p[5] to p[99] even though your array only has 5 elements.

a = rand ()% 999;

^This would actually give you a number in the range [0, 998]. You should use 1000 and not 999.

if ((p[i] % 3 == 0) && (p[i] % 2 == 0))

^This is looking for multiples of 6, not multiples of 3.

Your code also doesn't do what your assignment tells you to do: use a recursive function.
Last edited on
Okay thanks! Can you explain to me how I get the multiples of three instead of six? Also, can someone explain to me what recursion is?
Last edited on
if ((p[i] % 3 == 0)

I think @fg109 was wrong here. This checks for multiples of three not six. So you're doing good there.

Recursion.

I'll give you some links that explain it better than I ever could :)

https://www.youtube.com/watch?v=4agL-MQq05E&ab_channel=thenewboston

https://www.youtube.com/watch?v=RgCi5s8oITM&ab_channel=CodingMadeEasy

Its basically a function that calls itself over and over again. If you still dont understand it from these videos, try googling around, if you still dont get it, I'll try my best to explain :)
Yes, (p[i] % 3 == 0) is for a number that is divisible by 3, but (p[i] % 3 == 0) && (p[i] % 2 == 0) is for a number that is divisible by 3 and 2, which means a number divisible by 6.
oh yea you're right about that sorry. So remove the second condition if you only want multiple of six.
Thank you so much! This helped me out a lot.
Topic archived. No new replies allowed.