Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Dynamically allocating and filling array in a function example
- //Venix Cador
- //03/29/2012
- #include <iostream>
- #include "VarArray.h"
- using namespace std;
- void addNumber(int *& arrayptr, int number, int &size);
- void removeNumber(int *& arrayptr, int number, int &size);
- void output(int *arrayptr, int size);
- //Main fucntion
- int main(){
- int number,
- size = 0,
- *ptr = new int [size];
- char status = 'n';
- char action = 'a';
- do
- {
- cout <<"done? [y/n]: ";
- cin >> status;
- if(status == 'n'){
- cout << "add or remove? [a/r]: ";
- cin >> action;
- cout << "Input number: ";
- cin >> number;
- switch (action) {
- case 'a':
- addNumber(ptr,number, size);
- output(ptr, size);
- break;
- case 'r':
- removeNumber(ptr, number, size);
- output(ptr, size);
- break;
- default:
- cout << "Please enter a valid action!" << endl;
- }
- }
- }while( status == 'n');
- output(ptr, size);
- return 0;
- }
- //addNumber where you add the number and increase the size of the array
- void addNumber(int *& arrayptr, int number, int &size){
- // create a new array;
- //increment the size and copy the first array to the second one;
- int* ptr;
- ptr = new int[size + 1];
- for(int i = 0; i < size; i++) {
- ptr[i] = arrayptr[i];
- }
- //put the number inside the last element of ptr;
- //delete old array;
- ptr[size] = number;
- delete [] arrayptr;
- arrayptr = ptr;
- size++;
- }
- //this where you remove the number and decrease the size by one
- //the array shrink everytime you remove a number from the array
- void removeNumber(int *& arrayptr, int number, int &size){
- int* ptr;
- ptr = new int[size-1];
- int ptrcounter = 0;
- for(int i = 0; i < size; ++i){
- if (arrayptr[i] != number) {
- ptr[ptrcounter] = arrayptr[i];
- ptrcounter++;
- }
- }
- delete [] arrayptr;
- arrayptr = ptr;
- size--;
- }
- //That is where you the function printed the number in incresing order
- //It finds the smallest number to be output first.
- void output(int *arrayptr, int size) {
- int* ptr;
- int tempsize=size;
- ptr = new int [size];
- for(int i = 0; i < size; i++) {
- ptr[i] = arrayptr[i];
- }
- while(tempsize!=0){
- int smallest= ptr[0];
- for (int i = 0; i < tempsize; i++)
- if (ptr[i]<smallest)
- smallest=ptr[i];
- cout<<smallest<<" ";
- removeNumber(*&ptr, smallest, tempsize);
- }
- cout<<endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment