2D Arrays

Hi people I just started doing c++ and Im instructed to do this without any background hope you guys help me thanks.
This is the Instruction:
a 10 x 15 array is filled with random numbers between 10 and 100.
the 2D array is displayed on the screen in tabular form.
the user is asked to enter two numbers between 10 and 100
the program counts how many times the two numbers inputted occurs in the 2d array and displays the count on the screen.
the main() function should only contain variable declarations and functions calls.

this is what I did so far.

#include <stdio.h>
#include <stdlib.h>

int main(void) {
int i;
int a;
for (i = 1; i <= 150; i++) {

printf("%d ", 10 + (rand() % 90));

if (i % 15 == 0) {
printf("\n");
}
}
printf("\n Enter two numbers between 10 and 100: \n");
scanf("%d",a);
}
> Hi people I just started doing c++
The code you wrote is C code.

So let's clear up whether you want a C program or a C++ program.
Why printf() and scanf() - these are c functions. Have you come from a c background?

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>

constexpr size_t row_a {10}, col_a {15};
using Array = int[row_a][col_a];

int getInt(const std::string& prm)
{
	int i {};

	while ((std::cout << prm) && (!(std::cin >> i) || std::cin.peek() != '\n')) {
		std::cout << "Not an integer\n";
		std::cin.clear();
		std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
	}

	std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
	return i;
}

void init(Array a)
{
	for (size_t r = 0; r < row_a; ++r) {
		auto& ar {a[r]};

		for (size_t c = 0; c < col_a; ++c)
			ar[c] = rand() % 91 + 10;
	}
}

void display(const Array a)
{
	for (size_t r = 0; r < row_a; ++r) {
		auto& ar {a[r]};

		for (size_t c = 0; c < col_a; ++c)
			std::cout << ar[c] << ' ';

		std::cout << '\n';
	}
}

size_t find(const Array a, int n)
{
	size_t cnt {};

	for (size_t r = 0; r < row_a; ++r) {
		auto& ar {a[r]};

		for (size_t c = 0; c < col_a; ++c)
			cnt += ar[c] == n;
	}

	return cnt;
}

int main()
{
	const size_t r {10};
	const size_t c {15};

	int array[r][c] {};

	srand(static_cast<unsigned int>(std::time(nullptr)));

	init(array);
	display(array);

	const auto n1 {getInt("Enter first number: ")};
	const auto n2 {getInt("Enter second number: ")};

	std::cout << '\n' << n1 << " occurs " << find(array, n1) << " times\n";
	std::cout << '\n' << n2 << " occurs " << find(array, n2) << " times\n";
}

Topic archived. No new replies allowed.