i'm trying to write a program that reads numbers from a text file( 21 12 44 21 -5 63 0 ) to an array and bubble sort them in an descending order, and printing out only positive numbers. i have been trying for a while but what is displayed is not what i expect.
the contents of the text file are:
21 12 44 21 -5 63 0
the full code:
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <iomanip>
#include <conio.h>
using namespace std;
class bubble
{
public:
unsigned* arr;
int n;
//Constructor
bubble(const int& size) : n(size) { this->arr = new unsigned[n]; }
//function to read from file
void inputvf(istream &f)
{
//check if file is open
if (f.fail()) {
cout << "\n Error in openning file!!!";
exit(1);
}
for (int i = 0; i < n; i++)
f >> arr[i];
delete[] arr;
//close file
//f.close();
}
//Bubble sort function
void bubblesort()
{
for (int i = 1; i<n; i++)//for n-1 passes
{
for (int j = 0; j<n - 1; j++)
{
if (arr[j] < arr[j + 1])
{
int temp;
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
void display()
{
cout << endl;
cout << "----------------------\n";
cout << "Sorted array elements \n";
cout << "----------------------\n";
if (arr >= 0){
for (int j = 0; j < n; j++)
cout << arr[j] << endl;
}
}
};
int _tmain(int argc, _TCHAR* argv[])
{
bubble list(7);
ifstream file("Text.txt");
list.inputvf(file);
list.bubblesort();
list.display();
_getch();
return 0;
results after i run the code:
4277075694
1
4261281277
2880154539
2880154539
4277075694
0
what am i doing wrong??? please help
this is the new code(below):
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <iomanip>
#include <conio.h>
using namespace std;
class bubble
{
public:
//Array of integers to hold values
int* arr;
//Number of elements in array
int n;
//Constructor
bubble(const int& size) : n(size) { this->arr = new int[n]; }
//function to read from file
void inputvf(istream &f)
{
//check if file is open
if (f.fail()) {
cout << "\n Error in openning file!!!";
exit(1);
}
for (int i = 0; i < n; i++)
f >> arr[i];
//delete[] arr;
//close file
//f.close();
}
//Bubble sort function
void bubblesort()
{
for (int i = 1; i<n; i++)//for n-1 passes
{
for (int j = 0; j<n - 1; j++)
{
if (arr[j] < arr[j + 1])
{
int temp;
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
void display()
{
cout << endl;
cout << "----------------------\n";
cout << "Sorted array elements \n";
cout << "----------------------\n";
if (arr >= 0){
for (int j = 0; j < n; j++)
cout << arr[j] << endl;
}
}
};
int _tmain(int argc, _TCHAR* argv[])
{
bubble list(7);
ifstream file("Text.txt");
list.inputvf(file);
list.bubblesort();
list.display();
_getch();
return 0;
}
Two problems:
In inputvf:
delete[] arr;
You should not delete the array at this point - you haven't even started using it yet.
This declaration:
unsigned* arr;
means that all of your input is unsigned, which means -1 is read as 4294967291 and thus will be treated as a large number. Change your array to a normal int and then use an if test to ignore negative numbers when outputting.
Related
#include <iostream>
using namespace std;
int list [50];
void bsort(int list[], int n);
void printArray(int list[], int n);
int main ()
{
for (int i = 100; i > 50; i--)
{
list[i] = i;
cout << list[i] << endl;
}
int n = sizeof(list) / sizeof(list[0]);
bsort(list, n);
printArray(list, n);
return 0;
}
void bsort(int list[], int n)
{
int i, j;
for (i = 0; i <= 48; i++)
{
for (j = i+1; j <= 49; j++)
{
int temp;
if (list[i] > list[j])
{
temp = list[i];
list[i] = list [j];
list[j] = temp;
}
}
}
}
void printArray(int list[], int n)
{
for (int i = 0; i < n; i++)
cout << list[i] << " ";
cout << endl;
}
I'm in an intro-level computer science course and I am currently trying to write a program that calls the function 'bsort' to arrange the elements of the array 'list' in increasing order but my output is 49 zeros and I am not sure why? My professor wanted us to initialize the array 'list' starting at 100 and ending with 51 (in decreasing order).
Your initialisation loop is incorrect. Try like this
for (int i = 0; i < 50; i++)
{
list[i] = 100 - i;
cout << list[i] << endl;
}
Your version did list[100] = 100, list[99] = 99, etc but the array only has size 50.
I have a question about the exercise from my course:
Write a program that takes array of real numbers as parameter and replaces each element that is smaller than average of the first and last element, by this average. This is my code:
#include <iostream>
#include <string>
using namespace std;
void replaverage(int arr[], int n)
{
for (int i; i < 6; i++) {
cout << "Enter the numbers" << endl;
cin >> arr[i];
}
int f = arr[0];
int l = arr[n - 1];
double av = f + l / 2;
for (int i; i < n; i++) {
if (arr[i] < av) {
arr[i] = av;
}
}
}
int main()
{
int n;
int arr[n];
replaverage(arr, n);
cout << arr << " " << endl;
return 0;
}
Code is working, however as an output, it is giving some kind of address "0x7fff2306a5c0". I'm beginner so I apologize, maybe my error is stupid but I don't know how to fix it. Thanks for helping!
#include <iostream>
#include <string>
using namespace std;
void replaverage(int arr[], int n)
{
for (int i = 0; i < n; i++) {
cout << "Enter the number: ";
cin >> arr[i];
cout << endl;
}
int f = arr[0];
int l = arr[n - 1];
double av = (f + l) / 2;
for (int i = 0; i < n; i++) {
if (arr[i] < av) {
arr[i] = av;
}
}
}
int main()
{
int n = 6; // Making 6 since you had it hardcoded
int arr[n];
replaverage(arr, n);
for (int i = 0; i < n; i++) {
cout << arr[i] << endl;
}
return 0;
}
First problem: Initialize your loop counters to 0;
Second problem: Initialize n in main being passed as parameter to
something
Third problem: Your average calculation is incorrect. It should be (f+l) / 2. Otherwise it will be doing l/2 + f, which is incorrect.
Fourth problem: You need to loop over your array to see all the
elements
New to C++ and learning. This program returns the correct output. I changed the function prototype to void to isolate and make sure function is providing correct output.
#include <iostream>
#include <fstream>
void ArraySortToMedian(int x[], int numElem);
using namespace std;
int main()
{
ifstream infile;
infile.open("numbers.txt");
const int SIZE = 6;
int array[SIZE];
int i;
if(!infile)
{
cout << "couldn't find 'numbers.txt'";
return 1;
}
while(i < SIZE && infile >> array[i])
i++;
infile.close();
for(i = 0; i < SIZE; i++)
cout << array[i] << "\n";
ArraySortToMedian(array, SIZE);
return 0;
}
void ArraySortToMedian(int x[], int numElem)
{
bool swap;
int temp, i;
double m;
do
{
swap = false;
for(i = 0;i < (numElem - 1); i++)
{
if( x[i] > x[i + 1] )
{
temp = x[i];
x[i] = x[i + 1];
x[i + 1] = temp;
swap = true;
}
}
}
while (swap);
cout << "\n";
for(i = 0; i < numElem; i++)
cout << x[i] << "\n";
m = (x[numElem/2] + x[numElem/2]-1)/(double)2;
cout << "\n" << m;
}
Output:
6
5
3
1
2
4
1
2
3
4
5
6
3.5
When I remove void and replace it with double to return to main() the median value like this.
#include <iostream>
#include <fstream>
double ArraySortToMedian(int x[], int numElem);
using namespace std;
int main()
{
ifstream infile;
infile.open("numbers.txt");
const int SIZE = 6;
int array[SIZE];
int i;
double median;
if(!infile)
{
cout << "couldn't find 'numbers.txt'";
return 1;
}
while(i < SIZE && infile >> array[i])
i++;
infile.close();
for(i = 0; i < SIZE; i++)
cout << array[i] << "\n";
median=ArraySortToMedian(array, SIZE);
cout<< "\n" << median << "\n";
return 0;
}
double ArraySortToMedian(int x[], int numElem)
{
bool swap;
int temp, i;
double m;
do
{
swap = false;
for(i = 0;i < (numElem - 1); i++)
{
if( x[i] > x[i + 1] )
{
temp = x[i];
x[i] = x[i + 1];
x[i + 1] = temp;
swap = true;
}
}
}
while (swap);
cout << "\n";
for(i = 0; i < numElem; i++)
cout << x[i] << "\n";
m = (x[numElem/2] + x[numElem/2]-1)/(double)2;
return(m);
}
Distorted Output:
1
6
5
3
1
2
1
1
2
3
5
6
2.5
When returned its moving the elements of the array that are generated in main() when before when I simply outputted from ArraySortToMedian(). I assume that it has to do with me referencing the beginning address of the array first element.
Probably very simple but with my limited experience I'm at a loss with this behaviour. Any help so that I can learn what I'm doing wrong will be appreciated. Thank you.
The problem is your input loop:
int i;
// ... snip ...
while(i < SIZE && infile >> array[i])
i++;
You're never initializing i, so this is undefined behavior. Maybe it works maybe it doesn't.
If you used a std::vector instead of an array, this would be easier:
std::vector<int> values;
int next;
while (infile >> next) {
values.push_back(next);
}
And now you're neither size-limited nor do you have to worry about keeping track of an index.
I have to create a program that looks like the printout of a lotto ticket.
Yet I can't seem to get the "mega" number in the right place. We have to generate 5 random numbers between 1 and 56, then one more number between 1 and 44 (the mega number). So its supposed to look like this:
Yet for some reason the mega number always prints before the 5 random numbers generated between 1 and 56.
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "cs110a2.h"
using namespace std;
void fillup(int x[], int n, int from, int to)
{
for(int i = 0; i < n; i++)
{
x[i] = RAND(from,to);
}
cout <<" ";
cout << RAND(1,44);
}
int bubble_sort(int x[], int n)
{
for(int i = 0; i < n-1; i++)
{
int temp;
for(int j=i+1; j<n ; j++)
{
if(x[i] > x[j])
{
temp = x[i];
x[i] = x[j];
x[j] = temp;
}
}
}
return(0); //What! why?
}
void print(int x[], int n)
{
for(int i = 0; i < n; i++)
{
cout << x[i] <<" ";
}
cout << endl;
}
int main(int argc, char **argv)
{
srand(time(NULL));
cout <<" Mega" << endl;
for(int i = 0; i < atoi(argv[1]); i++)
{
int lotto[5];
fillup(lotto,5,1,56);
bubble_sort(lotto,5);
print(lotto,5);
}
return(0);
}
Move the last two lines from the fillup function to the end of the print function.
As it is now, you're printing the mega after GENERATING the numbers, not after printing them.
string formatting using the \t ( tab ) to place where it needs to be.
I'm writing a program that has a user input integers into an array, calls a function that removes duplicates from that array, and then prints out the modified array. When I run it, it lets me input values into the array, but then gives me a "Segmentation fault" error message when I'm done inputing values. What am I doing wrong?
Here is my code:
#include <iostream>
using namespace std;
void rmDup(int array[], int& size)
{
for (int i = 0; i < size; i++)
{
for (int j = i + 1; j < size; j++)
{
if (array[i] == array[j])
{
array[i - 1 ] = array[i];
size--;
}
}
}
}
int main()
{
const int CAPACITY = 100;
int values[CAPACITY], currentSize = 0, input;
cout << "Please enter a series of up to 100 integers. Press 'q' to quit. ";
while (cin >> input)
{
if (currentSize < CAPACITY)
{
values[currentSize] = input;
currentSize++;
}
}
rmDup(values, currentSize);
for (int k = 0; k < currentSize; k++)
{
cout << values[k];
}
return 0;
}
Thank you.
for (int i = 0; i < size; i++)
{
for (int j = i + 1; j < size; j++)
{
if (array[i] == array[j])
{
array[i - 1 ] = array[i]; /* WRONG! array[-1] = something */
size--;
}
}
}
If array[0] and array[1] are equal, array[0-1] = array[0], meaning that array[-1] = array[0]. You are not supposed to access array[-1].
I wouldn't make it even possible to create duplicates:
int main()
{
const int CAPACITY = 100;
cout << "Please enter a series of up to 100 integers. Press 'q' to quit. ";
std::set<int> myInts;
int input;
while (std::cin >> input && input != 'q' && myInts.size() <= CAPACITY) //note: 113 stops the loop, too!
myInts.insert(input);
std::cout << "Count: " << myInts.size();
}
And do yourself a favour and don't use raw arrays. Check out the STL.
#include <algorithm>
#include <iostream>
#include <iterator>
using namespace std;
int main()
{
vector<int> vec = {1,1,2,3,3,4,4,5,6,6};
auto it = vec.begin();
while(it != vec.end())
{
it = adjacent_find(vec.begin(),vec.end());
if(it != vec.end())
vec.erase(it);
continue;
}
for_each(vec.begin(),vec.end(),[](const int elem){cout << elem;});
return 0;
}
This code compiles with C++11.
#include<iostream>
#include<stdio.h>
using namespace std;
int arr[10];
int n;
void RemoveDuplicates(int arr[]);
void Print(int arr[]);
int main()
{
cout<<"enter size of an array"<<endl;
cin>>n;
cout<<"enter array elements:-"<<endl;
for(int i=0;i<n ;i++)
{
cin>>arr[i];
}
RemoveDuplicates(arr);
Print(arr);
}
void RemoveDuplicates(int arr[])
{
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;)
{
if(arr[i]==arr[j])
{
for(int k=j;k<n;k++)
{
arr[k]=arr[k+1];
}
n--;
}
else
j++;
}
}
}
void Print(int arr[])
{
for(int i=0;i<n;i++)
{
cout<<arr[i]<<" ";
}
}