Finding number of occurence of a given number in an array - c++

I'm testing a recursive function that returns the number of occurrence of a given number in an array. I get an unexpected result when I run the code.
#include <iostream.h>
int Occurence(int A[], int size, int n)
{
static int occur=0;
if(size == 0)
{
int occur2 = (int) occur;
return occur2;
}
else
{
if ( n == A[size-1])
occur++;
Occurence(A, size-1, n);
}
}
int main()
{
int A[] = {1,3,2,5,1,2, 3, 7,7, 8,8, 4, 6, 9,9, 0};
int size = sizeof(A)/sizeof(A[0]);
int n;
cout<< "Enter Number to Find : ";
cin >>n;
cout<<endl;
cout<<"Number of Occurence of "<< n << " is :"<< Occurence(A, size, n)<<endl;
return 0;
}

You are missing a return at the end of your function. If size is not 0 then the behaviour of your function is undefined. Adding the return should make it work:
int Occurence(int A[], int size, int n)
{
static int occur=0;
if(size == 0)
{
int occur2 = (int) occur;
return occur2;
}
else
{
if ( n == A[size-1])
occur++;
return Occurence(A, size-1, n);
}
}
Recursion is a very strange way to implement this problem so I assume this is some toy example to demonstrate how recursion works. Even if this is the case you really shouldn't be using a static variable in your implementation. Just make each call return the current sum instead:
int Occurence(int A[], int size, int n)
{
if(size == 0)
{
return 0;
}
else
{
return (n == A[size-1] ? 1 : 0) + Occurence(A, size-1, n);
}
}
This version will return the correct result when called multiple times whereas your original would add to the previous count each time.
In real code simply do:
#include <algorithm>
int Occurence(int A[], int size, int n)
{
return std::count(A, A+size, n);
}

There are some compilation problems in your code. First of all, in C++, the standard library files usually don't have an extension in the filename. So, including <iostream.h> is wrong. You should include <iostream>.
Other problem with your code is that you are using cout and cin without specifying their namespaces. So, instead of using cout and cin directly, use std::cout and std::cin or declare use namespace std after your includes.
EDIT: as Thomas Matthews pointed out, prefer using std::cout and std::cin over using namespace std.

Related

Why am I getting a segmentation fault? What am I doing wrong?

Problem: A program to count the number of times a number repeats in an array using recursion.
What I've done: I've tried every way I know, I've gone with an output array for storing indices of the number, and just ++ to another number on finding a match to current number. Nothing seems to work, it's one error or another (I'm a noob). I tried looking for solutions online, found solutions on 3-4 websites but had no clue what was going on.
Here's the code:
#include <iostream>
using namespace std;
int ind(int a[], int size, int x){
int j;
if(size == 0){
return 0;}
else if (a[0]==x){
j++;
return j;
}
reind(a++,size—,x);
}
int main(){
int a[5] = {1,2,3,3,5};
ind(a, 5, 3);
}
Edit: That "reind" was a typo, I still get segmentation fault with "ind". Sorry for that.
There are quite a number of mistakes in this code:
j is uninitialized, and even if it weren’t, you are not using the value of j correctly.
There is a missing return on the recursive call to ind() (is that what the re was supposed to be?).
You are passing the original values of a and size to the recursive ind(), causing an endless loop. You are using the post-increment and post-decrement operators, which return the original values, not the new values. You would need to use the pre-increment and pre-decrement operators instead. Which is a bit overkill in this situation, as you don’t use the variables anymore after they are adjusted. So simple addition and subtraction operators can be used instead.
main() is ignoring the return value of ind().
Try this instead:
#include <iostream>
using namespace std;
int ind(int a[], int size, int x){
int j = 0;
if (size == 0){
return 0;
}
if (a[0] == x){
++j;
}
return j + ind(a+1, size-1, x);
}
int main(){
int a[5] = {1, 2, 3, 3, 5};
cout << ind(a, 5, 3);
}
Live Demo
That being said, j and the 2nd if can be eliminated completely:
int ind(int a[], int size, int x){
if (size == 0){
return 0;
}
return (a[0] == x ? 1 : 0) + ind(a+1, size-1, x);
}
Or:
int ind(int a[], int size, int x){
if (size == 0){
return 0;
}
return int(a[0] == x) + ind(a+1, size-1, x);
}

Finding minimum and maximum in a array c++

I have to find the minimum and maximum value of elements in a array using divide and conquer. I have written a code but it is not working for more then 6 elements in array. I don't know whats the problem
#include<iostream>
using namespace std;
int minimum=999,maximum,mi,ma;
void result(int mi,int ma)
{
if(maximum<ma)
{
maximum=ma;
}
if(minimum>mi)
{
minimum=mi;
}
}
void maxmin(int arr[],int i,int j)
{
cout<<" i ="<<i<<" j= "<<j<<endl;
if(i==j)
{
mi=ma=arr[i];
result(mi,ma);
}
else if(i==j-1)
{
if(arr[i]>arr[j])
{
ma=arr[i];
mi=arr[j];
}
else
{
mi=arr[i];
ma=arr[j];
}
result(mi,ma);
}
else
{
int mid=i+j/2;
maxmin(arr,i,mid);
maxmin(arr,mid+1,j);
}
}
int main()
{
int arr[10],n;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
maxmin(arr,0,n-1);
cout<<" max "<<maximum<<" min "<<minimum<<endl;
return 0;
}
Your code has a few mistakes
Your code reads n from the user input, but you provided only 10 sized array, and user can try to input 10+ numbers, so we will have an undefined behavior in that case.
You write it very bad and unreadable. If you want somebody else to read your code, check in the your favourite book or in the internet information about how to write beautiful and readable code.
You implemented that algorithm yourself. It is a bad habit, use the standard library algorithms and you will not encounter such mistake.
.
#include <iostream> // std::cin, std::cout
#include <cstddef> // std::size_t
#include <algorithm> // std::min_element, std::max_element
int main ()
{
std::size_t array_size;
std::cin >> array_size;
int *some_array = new int[array_size]; // Allocate memory dynamically
for(std::size_t i = 0; i < array_size; ++i)
{
std::cin >> some_array[i];
}
/* Standard library operate on iterators, they are special classes
* that have interface that is similar in many cases to pointers (so we can use pointers as iterators).
* std::min/max_element needs one iterator for the sequence beginning
* and one iterator after the end. It returns iterator to a found element.
*/
int min = *std::min_element(some_array, some_array + array_size);
int max = *std::max_element(some_array, some_array + array_size);
delete[] some_array;
std::cout << "Min = " << min << std::endl << "Max = " << max;
std::cout << std::endl;
}
Code isn't well written and first dry run your code, you will find the problem easily.
Change
else
{
int mid=i+j/2;
maxmin(arr,i,mid);
maxmin(arr,mid+1,j);
}
To
else
{
int mid=(i+j)/2; /*** Adding brackets ***/
maxmin(arr,i,mid);
maxmin(arr,mid+1,j);
}
And check the logic for calling the result function (because according to your logic the two subsets are individually calculating MIN and MAX in itself not in whole array)

Output an array using recursion

I am trying to output a simple array using recursion and here is my code:
#include <iostream>
using namespace std;
int first7(int *aptr, int n) {
if(n == 0){
return 0;
}
first7(aptr+1,n-1);
cout<<*aptr;
return 0;
}
int main(){
int arr[50],n;
cin>>n;
for(int i=0; i<n; i++){
cin>>arr[i];
}
first7(arr, n);
return 0;
}
I wished to output it starting from 0th index. but it turned out to be opposite.
1.please tell me what is wrong with my code?
2.what should i do to display it starting from the 0th index and so on
3.if i remove the return 0 statement after the cout statement, then also it works fine. How is it?
You need to print the item before you recurse:
void first7(int *aptr, int n)
{
if(n == 0)
{
return;
}
cout << *aptr;
first7(aptr+1, n-1);
}
Note that there's also no need to return a value, so I've removed that.
If you want to output the array in reverse order then just do the recursion before the printing:
void first7(int *aptr, int n)
{
if(n == 0)
{
return;
}
first7(aptr+1, n-1);
cout << *aptr;
}
You've asked about the return statement in the comments. You only need a return statement to exit before the end of the function. When the functions gets to the last line it will automatically return without you having to do anything about it. If you're unsure about this then just run the code through a debugger and see what happens.

bubble sorting an array using recursion (no loops) c++

#include <iostream>
#include <cstdlib>
using std:: cin;
using std:: cout;
using std:: endl;
const int N=10;
void readarray(int array[], int N);
int bubble_sort (int array[], int size, int round,
int place);
int main ()
{
int array[N];
readarray( array, N );
int round, place;
cout << bubble_sort(array, N, place, round);
return EXIT_SUCCESS;
}
void readarray(int array[], int N)
{
int i=0;
if (i < N)
{
cin >> array[i];
readarray(array+1, N-1);
}
}
int bubble_sort (int array[], int size, int round,
int place)
{
round =0;
place =0;
if (round < N-1) // this goes over the array again making sure it has
// sorted from lowest to highest
{
if (place < N - round -1) // this sorts the array only 2 cells at a
// time
if (array[0] > array[1])
{
int temp = array[1];
array[1]=array[0];
array[0]=temp;
return (array+1, size-1, place+1, round);
}
return (array+1, size-1, place, round+1);
}
}
I know how to do a bubble sort using two for loops and I want to do it using recursion. Using loops you require two for loops and I figured for recursion it might also need two recursive functions/calls. This is what I have so far. The problem is that its outputting only one number, which is either 1 or 0. I'm not sure if my returns are correct.
In c++11, you can do this:
#include <iostream>
#include <vector>
void swap(std::vector<int &numbers, size_t i, size_t j)
{
int t = numbers[i];
numbers[i] = numbers[j];
numbers[j] = t;
}
bool bubble_once(std::vector<int> &numbers, size_t at)
{
if (at >= numbers.size() - 1)
return false;
bool bubbled = numbers[at] > numbers[at+1];
if (bubbled)
swap(numbers, at, at+1);
return bubbled or bubble_once(numbers, at + 1);
}
void bubble_sort(std::vector<int> &numbers)
{
if ( bubble_once(numbers, 0) )
bubble_sort(numbers);
}
int main() {
std::vector<int> numbers = {1,4,3,6,2,3,7,8,3};
bubble_sort(numbers);
for (size_t i=0; i != numbers.size(); ++i)
std::cout << numbers[i] << ' ';
}
In general you can replace each loop by a recursive function which:
check the guard -> if fail return.
else execute body
recursively call function, typically with an incremented counter or something.
However, to prevent a(n actual) stack overflow, avoiding recursion where loops are equally adequate is good practice. Moreover, a loop has a very canonical form and hence is easy to read for many programmers, whereas recursion can be done in many, and hence is harder to read, test and verify. Oh, and recursion is typically slower as it needs to create a new stackframe (citation needed, not too sure).
EDIT
Using a plain array:
#include <iostream>
#include <vector>
#define N 10
void swap(int *numbers, size_t i, size_t j)
{
int t = numbers[i];
numbers[i] = numbers[j];
numbers[j] = t;
}
bool bubble_once(int *numbers, size_t at)
{
if (at >= N - 1)
return false;
bool bubbled = numbers[at] > numbers[at+1];
if (bubbled)
swap(numbers, at, at+1);
return bubbled or bubble_once(numbers, at + 1);
}
void bubble_sort(int *numbers)
{
if ( bubble_once(numbers, 0) )
bubble_sort(numbers);
}
int main() {
int numbers[N] = {1,4,3,6,2,3,7,8,3,5};
bubble_sort(numbers);
for (size_t i=0; i != N; ++i)
std::cout << numbers[i] << ' ';
}
Please read this post
function pass(i,j,n,arr)
{
if(arr[i]>arr(j))
swap(arr[i],arr[j]);
if(j==n)
{
j=0;
i=i+1;
}
if(i==n+1)
return arr;
return pass(i,j+1,n,arr);
}

inputting an array and finding if a number is in that array (all using recursion) c++

#include <iostream>
#include <cstdlib>
using std:: cin;
using std:: cout;
using std:: endl;
const int N=10;
void readarray(int array[], int N);
int find_num(int array[], int size);
int main ()
{
int array[N];
readarray (array, N);
cout << find_num(array, N);
return EXIT_SUCCESS;
}
void readarray(int array[], int N)
// this function is for inputting an array also using recursion
{
int i=0;
if (i < N)
{
cin >> array[i];
readarray(array+1, N-1);
}
}
int find_num(int array[], int size)
// this function is for checking if a number is in the array that
// was inputted
{
int n;
cin >> n;
if (n==array[0])
return 1;
else if (n!=array[0]){
find_num(array+1, size-1);
return 1;
}
else return 0;
}
Obviously, the whole point of the program is to only use recursion. I am having a problem with the the second function which is supposed to be checking if a number is found in the array or not. If the number has been found in the array then the output will be 1 if not then it should be 0. The problem is, it seems like it is taking more inputs than it should be and always outputs the number 1 (regardless if the number was found or not). I believe I am missing a small step. I do also want to ask if the void function is correct as well (seems like its working fine to me). thanks.
There are two termination criteria for your recursive function.
If you reache the end of the array, you haven't found the number n and return 0.
If you found the number n return 1.
If you not reache the end of the array and the number was not found, call your function rcursive, get the result and return it.
Apart from this the number you are searching for has to be an input to your function find_num. You don`t want to ask for a number again and again.
int find_num(int n, int array[], int size)
{
if ( size == 0 )
return 0; // end of array, n was not found
if ( n == array[0] )
return 1; // n was found
return find_num( n, array+1, size-1 ); // test next element of array
}
void readarray(int array[], int N)
{
if ( N > 0 )
{
cin >> array[0];
readarray( array+1, N-1 );
}
}
int main ()
{
int array[N];
readarray( array, N );
int n;
cin >> n;
cout << find_num( n, array, N );
return EXIT_SUCCESS;
}