#include <string.h>
#include "BubbleSort.h"
void BubbleSort(char Str[])
{
int i;
int NumElements;
bool Sorted;
char Temp;
NumElements = strlen(Str);
do {
Sorted = true;
NumElements--;
for (i = 0; i < NumElements; i++)
if (Str[i] > Str[i + 1])
{
Temp = Str[i];
Str[i] = Str[i + 1];
Str[i + 1] = Temp;
Sorted = false;
}
} while (!Sorted);
}
/////////////////////////////////////////////
#include <iostream>
#include "Bubblesort.h"
using namespace std;
void main() {
int Num;
char Array[20];
cout << "How many numbers would you like to enter?" << endl;
cin >> Num;
cout << "Enter your numbers:" << endl;
for (int i = 0; i < Num; i++)
{
cin >> Array[i];
}
cout << "Here are the numbers you entered:" << endl;
for (int i = 0; i < Num; i++)
{
cout << Array[i] << " ";
}
cout << endl << endl;
BubbleSort (Array);
cout << "Here are your sorted numbers:" << endl;
for (int i = 0; i < Num; i++)
{
cout << Array[i] << " ";
}
cout << endl;
}
////////////////////////////////////////////////////////
#ifndef BUBBLE_SORT_H
#define BUBBLE_SORT_H
void BubbleSort(char[]);
#endif
I get a Run Time Error stating that Num was corrupted. Can anyone help pinpoint the problem in my code?
Thanks
char Array[20] while the Num you input is larger than 20, it will corrupt.
Better use vector and push_back
One mistake is that you're calling strlen on a char array that is not guaranteed to be NULL terminated:
NumElements = strlen(Str);
Thus NumElements has an undetermined value.
You need to either:
1) pass the actual number of characters that are to be sorted as a parameter, along with the array and getting rid of the call to strlen:
BubbleSort(Array, Num);
//...
void BubbleSort(char Str[], int NumElements)
or
2) Make sure the char array you're passing is null terminated
Related
I need to write a C++ program where it swaps between two 1-dimensional
arrays using pointers and functions. Firstly, a void function named showValues to display both arrays before swapping takes and also a void function named swap to swap the elements between both arrays.
My question is: I'm supposed to swap the function but for some reason it wont run and I am not sure where is the error in my code
#include <iostream>
#include <iomanip>
using namespace std;
const int SIZE = 5;
void showValues(int[],int[]);
void swap(int[],int[]);
int main() {
int array1[SIZE] = {10,20,30,40,50};
int array2[SIZE] = {60,70,80,90,100};
showValues (array1, array2);
swap(array1, array2);
return 0;
}
void showValues(int array1[], int array2[]){
cout<<"The original arrays are as shown below: " << endl;
cout << " Array 1 is: ";
for (int i = 0; i < 5; ++i) {
cout << array1[i] << " ";
}
cout << "\n Array 2 is: ";
for (int i = 0; i < 5; ++i) {
cout << array2[i] << " ";
}
}
void swap(int array1[], int array2[])
{
int temp,i;
for(i=0; i<5; ++i)
{
temp = array1[SIZE];
array1[SIZE] = array2[SIZE];
array2[SIZE] = temp;
}
cout << "\nThe swapped arrays are as shown below: " << endl;
cout << " Array 1 is: ";
for (int i = 0; i < 5; ++i) {
cout << array1[i] << " ";
}
cout << "\n Array 2 is: ";
for (int i = 0; i < 5; ++i) {
cout << array2[i] << " ";
}
}
This part of your code doesn't make sense:
temp = array1[SIZE];
array1[SIZE] = array2[SIZE];
array2[SIZE] = temp;
SIZE is 5. So, you are accessing array1[5] and array2[5], i.e. the 6th element of the array. Yet, your arrays have only 5 elements to begin with (array1[0] to array1[4], same for array2), so you are accessing elements beyond the end of the array, which is undefined behavior that is probably just corrupting memory somewhere!
You probably meant to use i here, not SIZE, then the code makes sense. Instead, it would be useful to replace the "magic number" 5 with SIZE:
for(i = 0; i < SIZE; ++i)
{
temp = array1[i];
array1[i] = array2[i];
array2[i] = temp;
}
The void swap(int array1[], int array2[]) function is where you are having trouble. You actually don't even need to have another function for the swapping. You could just use std::swap() which is defined in the #include <utility> header. Since both arrays have the same size.
For example you could do something along these lines:
#include <iostream>
#include <iomanip>
#include <utility>
const int SIZE = 5;
void showValues(int[], int[]);
void swap(int[], int[]);
int main() {
int array1[SIZE] = { 10,20,30,40,50 };
int array2[SIZE] = { 60,70,80,90,100 };
int n = sizeof(array1) / sizeof(array2[0]);
showValues(array1, array2);
std::swap(array1, array2);
std::cout << "\n\nThe swapped arrays are as shown below:\n ";
std::cout << "\nArray 1 is: ";
for (int i = 0; i < n; i++)
std::cout << array1[i] << ", ";
std::cout << "\nArray 2 is: ";
for (int i = 0; i < n; i++)
std::cout << array2[i] << ", ";
return 0;
}
void showValues(int array1[], int array2[]) {
std::cout << "The original arrays are as shown below: " << std::endl;
std::cout << "\nArray 1 is: ";
for (int i = 0; i < 5; ++i) {
std::cout << array1[i] << " ";
}
std::cout << "\nArray 2 is: ";
for (int i = 0; i < 5; ++i) {
std::cout << array2[i] << " ";
}
}
Also consider not using using namespace std;.
For my lab in school I was asked to generate random numbers and characters and pass it into a function template and then sort them after showing my work as unsorted first. I'm using visual studios as a requirement for my school, but my main issue is that it's compiling with no errors but when I run my program it's not passing my array to be sorted. I've been spending a lot of time trying to understand why it's not working any help would be very appreciated.
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <algorithm>
using namespace std;
template <typename T>
void arrayIn(T arr[], int size, char word) {
if (word == 'd') {
sort(arr, arr + size, greater<>());
}
else {
sort(arr, arr + size);
}
return;
}
template <typename O>
void arr_out(O arr[], int size) {
int j;
for (j = 0; j < size; j++) {
cout << arr[j] << endl;
return;
}
delete[] arr;
}
int main(void) {
srand(time_t(NULL));
int size,i,j;
char word;
int *arr1;
char *arr2;
cout << "Enter in the size of the array: ";
cin >> size;
cout << "How would you like to sort in ascending or descending order?: ";
cin >> word;
arr1 = new int[size];
arr2 = new char[size];
if (arr1 == 0) {
cout << "memory allocation error";
system("pause");
exit(1);
}
cout << "The first array will sort intagers." << endl;
cout << "not sorted" << endl;
for (i = 0; i < size; i++) {
arr1[i] = rand() % 100 + 1;
cout << arr1[i] << endl;
}
arrayIn(arr1, size, word);
cout << "sorted" << endl;
arr_out(arr1,size);
if (arr2 == 0) {
cout << "memory allocation error";
system("pause`enter code here`");
exit(1);
}
cout << "the secound array will sort characters." << endl;
cout << "not sorted" << endl;
for (j = 0; j < size; j++) {
arr2[j] = rand() % (126 + 1 - 33) + 33;
cout << arr2[j] << endl;
}
arrayIn(arr2, size, word);
cout << "sorted" << endl;
arr_out(arr2, size);
system("pause");
return 0;
}
You have a very simple mistake in your arr_out function, which makes it only print the first element. Correct as follows (remove the line I commented out):
template <typename O>
void arr_out(O arr[], int size) {
int j;
for (j = 0; j < size; j++) {
cout << arr[j] << endl;
// return; // This will return after printing the first element!
}
delete[] arr;
}
I have this code of a dynamic array that I turned in as a lab. My instructor responded saying "wouldn't even compile, no resize of the array". I am having trouble dealing with the comment of "no resize of the array", meaning I have to add the ability to resize the array. Please help quick! (It does compile). Appreciate it.
I am supposed to make a program that asks the user to initially size the array. Create an array based on that size asking for a number, and insert the number. Then repeat getting and inserting a number, resizing the array as needed or until they enter -1 for the number.
Print the list.
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int count;
cout << "How many values do you want to store in your array?" << endl;
cin >> count;
int* DynamicArray;
DynamicArray = new int[count];
for (int i = 0; i < count; i++) {
cout << "Please input Values: " << endl;
cin >> DynamicArray[i];
{
if (DynamicArray[i] == -1) {
delete[] DynamicArray;
cout << "The program has ended" << endl;
exit(0);
}
else {
cout << endl;
}
}
}
for (int k = 0; k < count; k++) {
cout << DynamicArray[k] << endl;
}
delete[] DynamicArray;
return 0;
}
When the array is full, we need to resize it. Here is my solution
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
int main()
{
int count;
cout << "How many values do you want to store in your array?" << endl;
cin >> count;
if (count <= 0) {
cout << "The value should be greater than zero" << endl;
exit(0);
}
int* DynamicArray;
DynamicArray = new int[count];
int i = 0, value = 0;
while (1) {
cout << "Please input Values: " << endl;
cin >> value;
if (value == -1) {
cout << "The program has ended" << endl;
break;
}
else if (i < count)
{
DynamicArray[i++] = value;
}
else
{
// resize the array with double the old one
count = count * 2;
int *newArray = new int[count];
memcpy(newArray, DynamicArray, count * sizeof(int));
delete[]DynamicArray;
newArray[i++] = value;
DynamicArray = newArray;
}
}
for (int k = 0; k < i; k++) {
cout << DynamicArray[k] << endl;
}
delete[] DynamicArray;
return 0;
}
This question already has answers here:
How to make cin take only numbers
(2 answers)
Closed 6 years ago.
So the requirements for this program is to be able to increment arrays of the same size (size from 5 to 15 indexes) and increment each element in the array by one using for and while loops. The last task is to take values from the first array and put them in reverse order and assign them to the second array.
So everything works as normal, and the program rejects invalid inputs and does not go into an infinite loop. However, the program accepts some inputs that are not wanted.
For example, I would input something like '12 a' or '7 asdfkla;j lasnfg jasklgn asfg' and it would go through. It is interesting too because the code registers only 12 or 7 and completely ignores the rest. I think it is because once it hits a non-integer character, it would stop ignore the rest.
Why is it ignoring the rest of the input? And is there a way to catch this error from going through?
Also, if you see anything that catches your eye, feel free to critique c: I am always looking to improving.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
srand(time(NULL));
int x;
int j = 0;
bool not_valid = true;
system("color f");
cout << "Program will ask for an input for the size of an array.\n"
<< "With the array size defined, program will generate semi-\n"
<< "true random integers from 0 to 8. First array will then\n"
<< "be assigned to the second in reverse (descending) order.\n\n";
do {
cout << "Enter array size (0 - 15): ";
cin >> x;
if (x >= 5 && x <= 15) {
not_valid = false;
cout << "\nArray size: " << x << endl;
}
else {
cout << "Invalid input.\n\n";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
} while (not_valid);
int *arr0;
int *arr1;
arr0 = new int[x];
arr1 = new int[x];
for (int i = 0; i < x; i++) {
arr0[i] = rand() % 9;
}
for (int i = 0; i < x; i++) {
arr1[i] = rand() % 9;
}
cout << "\nARRAY 0 (unmodified, for):\n";
for (int i = 0; i < x; i++) {
cout << arr0[i] << "\t";
}
cout << "\n\nARRAY 0 (modified, for):\n";
for (int i = 0; i < x; i++) {
arr0[i]++;
cout << arr0[i] << "\t";
}
cout << "\n\nARRAY 1 (unmodified, while):\n";
for (int i = 0; i < x; i++) {
cout << arr1[i] << "\t";
}
cout << "\n\nARRAY 1 (modified, while):\n";
while (j < x) {
arr1[j]++;
cout << arr1[j] << "\t";
j++;
}
int second = x - 1;
for (int i = 0; i < x; i++) {
arr1[second] = arr0[i];
second--;
}
j = 0;
cout << "\n\nARRAY 1 (array 0, descending):\n";
while (j < x) {
cout << arr1[j] << "\t";
j++;
}
cout << endl << endl;
system("pause");
return 0;
}
Take input in string and then check if it's a number or not.
Example:
#include<iostream>
#include<sstream>
#include <string>
using namespace std;
int main()
{
string line;
int n;
bool flag=true;
do
{
cout << "Input: ";
getline(cin, line);
stringstream ss(line);
if (ss >> n)
{
if (ss.eof())
{
flag = false;
}
else
{
cout << "Invalid Input." << endl;
}
}
}while (flag);
cout << "Yo did it !";
}
I need help with getting this users input of an integer and retrieving the even numbers and displaying them with spaces.I already have the input processed into an array and have it reversed (thanks to stackoverflow) now need to extract the even numbers from the array and display them.
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
int evenNumbers(char even[], int num[], int indexing[]);
int main()
{
char integers[5];
int numbers[5];
int even[5] = {0,2,4,6,8};
int evens;
cout << "Please enter an integer and press <ENTER>: " << endl;
for (int j = 0; j < 5; j++)
cin >> integers[j];
for (int j = 0; j < 5; j++)
{
numbers[j]= integers[j] - '0';
}
cout << endl;
for (int j = 5; j > 0; j--)
{
cout << integers[j - 1] << " ";
}
cout << endl;
//having problems finding the even numbers and displaying the even numbers
//from the users input of integers, i have only learned how to display the
//subscript by a linear search
evens = evenNumbers(integers, numbers, even);
if (evens == -1)
cout << "There are no even numbers" << endl;
else
{
cout << "The even numbers are: " << (evens + 1) << endl;
}
system("pause");
return 0;
}
int evenNumbers(char even[], int num[], int indexing[])
{
int index = 0;
int position = -1;
bool found = false;
for (int j = 0; j < 5; j++)
{
num[j]= even[j] - '0';
}
while (index < 5)
{
if (num[index] == indexing[index])
{
found = true;
position = index;
}
index++;
}
return position;
}
If you want to display the even numbers from the array integers you can use a simple for loop and if statement:
for(int i = 4; i >= 0; i--)
{
if(integers[i] % 2 == 0)
cout << integers[i] << " ";
}
Your approach is all wrong, you can't detect even numbers by searching a list, you need a mathematical test for evenness. Write a function called is_even which tests one number and returns true if it is even and false if it is not. Then you can use that function, very simply, like this
for (int j = 0; j < 5; j++)
{
if (is_even(integers[j]))
cout << integers[j] << " ";
}
cout << endl;
Now you just need to write the is_even function.
void evennumbers(int num[])
{
for(int i=0;i<5;i++)
{
if(num[i]%2==0)
cout<<num[i]<<" ";
}
}
And avoid taking input to char what if user enters a number with more than one digit
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
void validNum(char valid[]);
void reverseNum(char rev[], int num2[]);
void evenNumbers(char even[], int num3[]);
void oddNumbers(char odd[], int num4[]);
int main()
{
char integer[5];
int number[5];
cout << "Your number is: ";
validNum(integer);
cout << "Your number in reverse is: ";
reverseNum(integer, number);
cout << "Even numbers: ";
evenNumbers(integer, number);
cout << endl;
cout << "Odd numbers: ";
oddNumbers(integer, number);
cout << endl;
system("pause");
return 0;
}
void validNum(char valid[])
{
char ch;
cout << "Please enter an integer and press <ENTER>: " << endl;
ch = cin.get;
while (ch < 0 || ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z')
{
cout << "ERROR: Please enter a positive integer and press <ENTER>: ";
for (int i = 0; i < 5; i++)
cin >> valid[i];
}
for (int j = 0; j < 5; j++)
{
cout << valid[j] - '0';
}
}
void reverseNum(char rev[], int num2[])
{
for (int j = 0; j < 5; j++)
{
num2[j]= rev[j] - '0';
}
cout << endl;
for (int j = 5; j > 0; j--)
{
cout << rev[j - 1]<< " ";
}
cout << endl;
}
void evenNumbers(char even[], int num3[])
{
for (int i = 0; i < 5; i++)
{
if (even[i] % 2 == 0)
{
cout << num3[i] << " ";
}
}
}
void oddNumbers(char odd[], int num4[])
{
for (int i = 0; i < 5; i++)
{
if (odd[i] % 2 == 1)
{
cout << num4[i] << " ";
}
}
}