Bubblesort and using array

Write a C++ program that will
• Ask the user how many whole numbers they wish to enter (max 20)
• Read that many numbers
• Print them in the order they were entered
• Sort them in order by increasing value, and print them in the sorted order

Use an array to store the integer values read.

Sorting will be done in a function where the array will be the first parameter and the number of integers entered into the array will be the second parameter.

Use the bubble sort algorithm discussed in the class.

I am extremely confused. The code below is what I managed to get but I have the numbers coded in as opposed to being able to be entered. How do I adjust my code below to fit the requirements from above?

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
  #include "stdafx.h"
#include <iostream>
using namespace std;

void bubble_sort(int arr[], int n)
{
	for (int i = 0; i < n; ++i)
		for (int j = 0; j < n - i - 1; ++j)
			if (arr[j] > arr[j + 1])
			{
				int temp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = temp;
			}
}

//Driver Function
int main()
{
	int input_ar[] = { 10, 50, 21, 2, 6, 66, 802, 75, 24, 170 };
	int n = sizeof(input_ar) / sizeof(input_ar[0]);
	bubble_sort(input_ar, n);
	cout << "Sorted Array : " << endl;
	for (int i = 0; i < n; ++i)
		cout << input_ar[i] << " ";
	return 0;
}
Ask the user how many whole numbers they wish to enter (max 20)

this implies the array would be a dynamic one with it's size determined by user-input at run-time:
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
#include <iostream>
//http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice
void bubble_sort(int* arr, const size_t n)
{
	for (int i = 0; i < n; ++i)
		for (int j = 0; j < n - i - 1; ++j)
			if (arr[j] > arr[j + 1])
			{
				int temp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = temp;
			}
}

//Driver Function
int main()
{
	//int input_ar[] = { 10, 50, 21, 2, 6, 66, 802, 75, 24, 170 };
	//int n = sizeof(input_ar) / sizeof(input_ar[0]);
	std::cout << "How many numbers would you like to enter (max 20)? \n";
	size_t num{};
	std::cin >> num;
	int* input_ar = new int [num]{};//dynamic array, each element initialized to 0
	for (size_t i = 0; i < num; ++ i)
    {
        std::cout << "Enter element " << i + 1 << " of the array \n";
        std::cin >> input_ar[i];
    }
	bubble_sort(input_ar, num);
	std::cout << "Sorted Array : " << std::endl;
	for (int i = 0; i < num; ++i)
    {
        std::cout << input_ar[i] << " ";
    }

    delete [] input_ar;//release allocated memory
	return 0;
}
Topic archived. No new replies allowed.