Removing an element from array without any built-in function in c++ - c++

The question is:
"Write and test the following function that removes items from an array:
void removeAll(float a[], int& n, float x);
The function removes all occurrences of x among the first n elements of the array and decreases the value of n by the number removed.
I have written a code and it works perfectly fine. Basically, I tagged the value whose occurrences the user wants to remove with Zero and the code skips printing when it encounters zero. Basically we are not removing that value from the array just replacing it with some other value. What if the user entered zero in the array? then the other zeroes will also be skipped which I don't want them too. how can I do this?
Here is my code:
Don't use any classes, objects, vectors, strings nor any function in c++ which is like array.splice in js.
#include<iostream>
using namespace std;
void removeAll(float a[], int &n, float x)
{
for (int i = 0; i < n; i++)
{
if (a[i] == x)
{
a[i] = 0;
}
}
for (int i = 0; i < 10; i++)
{
if (a[i]!=0)
cout << a[i] << endl;
}
}
int main()
{
float a[10], x;
int n;
cout << "Enter values in array: \n";
for (int i = 0; i < 10; i++)
{
cin >> a[i];
}
cout << "Enter the value whose occurrence you want to remove from the array: ";
cin >> x;
cout << "Enter serial no. uptill which you want to remove the occurences";
cin >> n;
removeAll(a, n, x);
}

If you just want to print out the array without a chosen variable you can do it with one condition:
void removeAll(float a[], int &n, float x)
{
for (int i = 0; i < n; i++)
{
if (a[i] == x)
{
// Don't print it
}
else
{
cout << a[i] << endl;
}
}
}
If you want to eliminate the occurrences I would suggest to move the following numbers forward. I won't code it but here is an example:
array: 2,3,4,5,3,7
number to remove: 3
1. Iterate through the array and find '3'
2. If you find one, move all elements on the right side on step to left:
2 3 4 5 3 7 => 2 4 5 3 7 X
^
2 4 5 3 7 X => 2 4 5 7 X X
^
3. Count how many times you have done step two and return the new length/new array

To accomplish this you'll need to do 4 things:
Make a copy of n to hold the number of elements to iterate over: int size = n
Change your loop condition to consider this new element rather than n: i < size
Decrement n each time you replace a value in the nested if-statement
Remove the second for-loop (if you want to print out everything under n but the replaced numbers do that in an else-condition.)

Related

Find 4 if a given array has 4 consecutive values using functions (C++)

A quick disclaimer before you read ahead, this is a question regarding my homework and some of these requirements will be oddly specific
I am writing a code that takes the number of values from the user and this will be the array length. Then it will ask the user to input their numbers into the array. Then it uses a function to determine if the given array contains 4 of the same values consecutively.
This is an example output
//example 1
Enter the number of values: 8
Enter the values: 3 4 5 5 5 5 4 5
The list has consecutive fours
//example 2
Enter the number of values: 9
Enter the values: 3 4 5 8 5 5 4 4 5
The list has no consecutive fours
The problem with my code is that I need to make a function bool isConsecutiveFour(int values[][4])for the question to be completed. I have tried that and since the array that I am originally using for the user input is a 1-dimensional array, I don't think I can do it 2 dimensional. When I copy and paste the code all into the main function the code works but once I implement it into a function with the requirements, the code starts to not work as intended. In the place where the function is called, I am aware that there is a expected expression, the thing is that I am unsure on what to put there as the original array is 1D while the one in the given function is 2D.
#include <iostream>
using namespace std;
bool isConsecultiveFour(int values[][4]);
int main(){
int x, input;
cout<<"Enter the number of values: "<< endl;
cin >> x;
int arr[x];
cout<<"Enter the values: "<< endl;
for(int i = 0; i < x; i++){
cin>>input;
arr[i] = input;
}
cout<<" "<< endl;
//error on the second bracket states that it is expecting an expression
isConsecultiveFour(arr[x][]);
return 0;
}
bool isConsecultiveFour(int values[][4]){
int count = 1;
for(int i = 0; i < sizeof(values)/sizeof(values[0]); i++){
if(values[i] == values[i + 1]){
count++;
}
}
if(count == 4 ){
cout<<"The list has consecutive fours"<< endl;
}
else{
cout<<"The list has no consecitive fours"<< endl;
}
return count;
}
You have multiple problems in your code.
The main problem regarding variable-length arrays and size of an array in a function can be solved using std::vector.
The function should return a boolean.
You can leave the loop after the fourth consecutive value
You have to reset the counter if two consecutive values are different.
You don't need to flush the buffer with endl.
You should avoid using namespace std;.
The type of a size of a STL container or array is std::size_t.
The end of the loop was off by one.
#include <iostream>
#include <vector>
bool isConsecutiveFour(std::vector<int> values);
int main(){
std::size_t x;
std::cout<<"Enter the number of values: \n";
std::cin >> x;
std::vector<int> arr(x);
std::cout<<"Enter the values: \n";
for(auto &el : arr){
std::cin>>el;
}
std::cout<<" \n";
isConsecutiveFour(arr);
return 0;
}
bool isConsecutiveFour(std::vector<int> values){
int count = 1;
for(std::size_t i = 0; i + 1 < values.size(); i++){
if(values[i] == values[i + 1]){
count++;
} else {
count = 1;
}
if(count == 4 ){
std::cout<<"The list has consecutive fours\n";
return true;
}
}
std::cout<<"The list has no consecitive fours\n";
return false;
}

C++ Array Inputing and Reversing Values

For a project I need to write a program that reads in a series of positive integers, stored in an array, terminated by a -1. Then it should reverse the order of the array and print that along with the average of all the numbers.
ex: Input: 21 34 63
Output: 63 34 21 Ave: 39.3
I am not sure where to begin. I thought maybe getting a user input in a while loop. So,
int num, i;
const int SIZE = 9;
int arr [SIZE] = {i};
i = 1;
while(num !=-1){
cout << "Enter a number: ";
cin >> num;
arr[i] = num;
i++;
}
cout << arr;
Okay so, first how do I create an array that takes user inputs and stores it as separate variables in the array? (Above is my unsuccessful attempt at that.)
Thats a simple problem. You first need to take the input and then reverse it.
int num=0, i,j,k;
const int SIZE = 99; //any upperbound value, just to ensure user doesnt enter more values then size of array
int arr [SIZE] = {0}; //better to initialize with 0
i = 0; //considering 0 indexed
int sum=0; // for average
while(num !=-1){
cout << "Enter a number: ";
cin >> num;
if(num!=-1)
{
arr[i] = num;
sum+=num;
}
i++;
}
int temp;
//now reversing
// size of the input array is now i
for(j=0,k=i-1;j<k;j++,k--)
{
temp=arr[j];
arr[j]=arr[k];
arr[k]=temp;
}
//what i am doing here is- keeping the index j on the beginning of the
//array and k to the end of the array. Then swap the values at j and k, then
//increase j and decrease k to move to next pair of points. We do this until j is
//less then k, means until we doesnt reach mid of the array
//printing the reversed array and average
cout<<"reversed array"<<endl;
for(j=0;j<i;j++)
cout<<arr[j]<<" ";
cout<<"average"<<float(sum)/i;
see the comments for suggestions
Since you are writing your program in c++, you should take a look at std::vector and the reverse function that the STL provides you.
Using the above tools the solution to your problem is the following:
#include <vector>//include to use std::vector
#include <algorithm>//include to use reverse
int main()
{
std::vector<int> v;
int i;
float sum = 0.0f;
while(std::cin>>i && i != -1)
{
v.push_back(i);
sum+=i;
}
reverse(v.begin(),v.end());
for(int num : v)
std::cout<<num<<" ";
std::cout<<"average:"<<sum/v.size()<<std::endl;
}

How to make arrays behave like vectors?

I want to have an array with initial size 4. The user can add as many elements(int type) to it. The function append() will be used for it. Also every time the size of the array is insufficient the same function will double its size and add the element to it.
#include <iostream>
using namespace std;
int n = 4;
int count = 0;
void append(int *a, int k)
{
if(count == n)
{
n *= 2;
int *b = new int[n];
for(int i = 0; i < count; ++i)
{
b[i] = a[i];
}
a = b;
}
a[count] = k;
++count;
}
void display(int *a)
{
for(int i = 0; i < count; ++i)
cout << a[i] << endl;
}
int main()
{
int *array = new int[n];
char t = 'y';
int num;
while(t != 'n')
{
cout << "Enter Value: ";
cin >> num;
append(array, num);
cout << "Do you want to enter more values?(y/n): ";
cin >> t;
}
cout << "The values entered are:\n";
display(array);
return 0;
}
After giving the following values for entering into the array:
1
2
3
4
5
6
7
8
8
9
10
11
12
13
15
I am getting the following output(using display() function)
1
2
3
4
0 [(This value depends on the compiler) #Erroneous Output]
6
7
8
1 [(This value depends on the compiler) #Erroneous Output]
10
11
12
13
14
15
I do not know why I am getting random values for the elements entered just after the array is updated(size is doubled), and how I should fix it.
Vectors, in essence are just dynamically allocated arrays. My question here is why not just use a vector with 4 slots initially. std::vector<int>(4); will do the trick although if you are adamant on remaking the vector class, research the topic of dynamic arrays and create a c++ template class based off them. According to my understanding .append() deallocates all elements in the vector, then reallocates them with the extra element at the end.
There are many articles online created by people trying to accomplish similar tasks, just do a little bit of digging around:
http://www.gamedev.net/topic/528822-c-writing-my-own-vector-class/
https://codereview.stackexchange.com/questions/50975/creating-a-custom-vector-class

Party Invitation

The problem that I am working on right now is here, but I am of course not looking for the complete answer to this homework problem. All I am asking for is the steps in the final parts of the question. This is what I have so far:
int main()
{
cout << "Please enter the number of guests attending your party: ";
int k;
cin >> k;
cout << "Please enter the number of rounds of removal you'd like to perform: ";
int m;
cin >> m;
for (int i = 1; i <= m; i++) {
cout << "Please enter the multiple at which you'd like the removal to be at for round " << i << ": ";
int r;
cin >> r;
if (k % r == 0) {
k - r;
}
cout << k << endl;
}
system("pause");
}
This is all so confusing to me, and I truly have no idea where to turn to get answers. It seems like I'd need an array to solve this, but arrays in C++ cannot be variable, and the array length would be k, a variable input. Any help would be very appreciated.
I've read that question. you need a dynamic list like Linked list because you need to put and remove different items from different index so using arrays will be difficult.
Try to use std::vector or std::list, you can add or remove any any of list
#include <list>
std::list<int> mylist;
How can you add and remove values from list, check this link http://en.cppreference.com/w/cpp/container/list
For using your own Linklist, check this link How could i create a list in c++?
According to your question an std::vector will be the best choice because it is a combination of an array & linked list in raw terms or we can simply say it's a dynamic array.
However as you mentioned n your comment that you haven't been taught anything other than basic arrays & want a solution within whatever you have learnt, then you have to take an array. Now the problem is that arrays are static & you cannot delete elements from it. So all you can do is to keep a counter that will take care of the number of elements in it.
// array insert and delete
#include <iostream>
using namespace std;
void see_array (int a[], int f, int b)
{
for (int i=f; i<b; ++i)
cout << a[i] << ' ';
cout << '\n';
}
int get_pos (int a[], int f, int b, int num)
{
for (int i=f; i<b; ++i)
{
if (a[i] == num)
return i;
}
return -1; // if search is unsuccessful
}
int main()
{
int a[] = {1,2,3,4,5,6,7,8,9,10};
int front = 0, back = 10; // as we have 10 elements
// delete last element
--back;
see_array(a, front, back);
// delete first element
++front;
see_array(a, front, back);
// delete element from middle say 6
int pos = get_pos(a, front, back, 6);
if (pos != -1)
{
for (int i = pos; i<back; ++i) // shift elements towards left
{
a[i] = a[i+1];
}
--back; // decrease size of the array
see_array(a, front, back);
}
return 0;
}
/* Output :-
1 2 3 4 5 6 7 8 9
2 3 4 5 6 7 8 9
2 3 4 5 7 8 9
*/
I hope the above program is of some help to you !!! Good luck !!!

recursive algorithm to sum of every element in an array with a value lesser than x

I'm a beginner to c++ and I'm trying to write an recursive algorithm that returns the sum of every element in an array with a value less than x.
Here is my code:
#include <iostream>
using namespace std;
int sumOfElement(int xList[],int x, int lengthOfArray){
int sum = 0;
if (lengthOfArray == 0)
return sum;
else
for (int i=0; i <= lengthOfArray; i++) {
if(xList[i] < x)
return sum + xList[i];
else
sumOfElement(xList,x,lengthOfArray-1);
}
}
int main() {
cout << "Size of Array: ";
int size;
cin >> size;
int *xList = new int[size];
//Inputing array.
cout << "Enter elements of array followed by spaces: ";
for (int i = 0; i<size; i++)
cin >> xList[i];
cout << "Enter the integer value of x: " <<endl;
int limit;
cin >> limit;
cout << "Sum of every element in an array with a value less than x: " << sumOfElement(xList,limit,size) << endl;
return 0;
}
I'm using Visual Studio, while I was running the code, I got this warning: "warning C4715: 'sumOfElement' : not all control paths return a value. " And the program always stop executing when it asks me to enter the integer value for x.
What's wrong with my code?
Your approach here isn't really recursive. The idea with recursion is to consider a base case, and then consider how to reduce the problem at each step until you get to the base case.
For this problem:
The base case is when the length of the array is zero. In this case we return a sum of zero. (Intuitively: if the array is empty then we're adding nothing, giving a sum of zero.)
In order to reduce our array we look at the last element of the array (ie. at lengthOfArray - 1). We process this element: if it's less than x we add it, if it's not then we ignore it. We then get the result of processing the rest of the array by the same means (by calling the same function, but with a different array length), and add our result if applicable.
So, some example code:
int sumOfElement(int xList[], int x, int lengthOfArray){
if (lengthOfArray == 0) {
// base case
return 0;
} else {
int value = xList[lengthOfArray-1];
if (value < x) {
// process the rest of the array and add our result
return value + sumOfElement(xList, x, lengthOfArray - 1);
} else {
// process the rest of the array
return sumOfElement(xList, x, lengthOfArray - 1);
}
}
}
for (int i=0; i <= lengthOfArray; i++)
{
if(xList[i] < x)
return sum + xList[i];
else sumOfElement(xList,x,lengthOfArray-1);
}
You shouldn't have a for-loop, and recursive functions should "return" the deeper call, so
int retVal = 0;
if(xList[lengthOfArray-1] < x)
retval = xList[lengthOfArray-1]
return retVal + sumOfElement(xList,x,lengthOfArray-1);