Output an array using recursion - c++

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.

Related

How do I fix this warning - "control reaches end of non-void function [-Wreturn-type]"

During compiling, it shows this warning - control reaches end of non-void function [-Wreturn-type]. I googled and found that this warning shows when you don't return anything in the function. But I couldn't figure out where's the error in my code.
Here's my code:
#include <iostream>
#include <algorithm>
using namespace std;
int findUnique(int *a, int n){
sort(a, a+n);
int i=0;
while(i<n){
if(a[i]==a[i+1]){
i += 2;
}
else{
return a[i];
}
}
}
int main(){
int t;
cin >> t;
while (t--){
int size;
cin >> size;
int *input = new int[size];
for (int i = 0; i < size; ++i)
{
cin >> input[i];
}
cout << findUnique(input, size) << endl;
}
return 0;
}
You have to know why this warning is shown to understand what to do about it, this warning is shown when your function has a return type but you haven't returned value from one or more exit points of a function. Now see in your function, you return a[i] but consider a situation where your code doesn't go in the else block at all. So after coming out of the while block. There is no return statement therefore compiler is throwing control reaches the end of non-void function [-Wreturn-type].
The function returns nothing in case when the array does not contain a unique number or when the parameter n is equal to 0.
So the compiler issues the warning message.
Moreover the while loop can invoke undefined behavior when i is equal to n-1 due to using a non-existent element with the index n in this if statement
if(a[i]==a[i+1]){
Also there is a logical error. The if statement
if(a[i]==a[i+1]){
i += 2;
}
else{
return a[i];
}
does not guarantee that indeed a unique number will be returned.
Using your approach when it is allowed to change the original array by calling the algorithm std::sort the function can be defined for example the following way
size_t findUnique( int *a, size_t n )
{
std::sort( a, a + n );
size_t i = 0;
bool unique = false;
while ( !unique && i != n )
{
size_t j = i++;
while ( i != n && a[i] == a[j] ) i++;
unique = i - j == 1;
}
return unique ? i - 1 : i;
}
And in main the function can be called like
size_t pos = findUnique(input, size);
if ( pos != size )
{
cout << input[pos] << endl;
}
else
{
// output a message that there is no unique number
}
Pay attention to that your program produces multiple memory leaks. You need to free the allocated memory in each iteration of the while loop.
The problem is in the function findUnique This function is supposed to return int no matter what although in your code you are returning an integer only under certain conditions
Here is a possible fix:
// return true if unique number found
// return false otherwise
bool findUnique(int *a, int n, int *unique){
sort(a, a+n);
int i=0;
while(i<n){
if(a[i]==a[i+1]){
i += 2;
}
else{
*unique = a[i];
return true;
}
}
return false;
}
Then in the main something like that:
int unique;
bool uniqueFound = findUnique(input, size &unique);
if (uniqueFound == true)
cout << unique << endl;
else
cout << "No unique number found" << endl;

How to solve RUN_ERROR even though it compiles normally?

I am currently writing a script about finding the nearest duplicate from a user entered size array.
The array must be between 1 and 10^5 and its value has to be between 1 and 10^5 also.
It compiles normally on my computer but whenever I submit it, it returns a run_error.
Here's what I wrote.
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
void input (int *);
int main(){
int n;
input (&n);
int a[n];
for(int i=0;i<n;i++){
if (scanf("%d",&a[i])!=1)
return 0;
if ((a[i]>100000)||(a[i]<1))
return 0;
}
for (int i=0;i<n;i++){
if (a[abs(a[i])]>=0){
a[abs(a[i])]=-a[abs(a[i])];
} else {
printf("%d",abs(a[i]));
return 0;
}
}
return 0;
}
void input(int *x){
if (scanf("%d",x)!=1)
exit(0);
if ((*x>100000)||(*x<1))
exit(0);
}
This program is logically incorrect. There is no connection between the size of the array defined in n and the limit of the allowed elements.
Since you have allowed a[i]>100000 to go up to 10^5 with no regards to the size of the array defined by a[n], the following access will attempt to access outside the bounds of the array, a[abs(a[i])] for any a[i] > n.
Also, you can pass by reference for syntactical simplicity
input(n);
void input(int &x){
if (scanf("%d",&x)!=1)
exit(0);
if (x>100000 ||x<1)
exit(0);
}
First of all, if you are writing in C, please tag this question as C question, and not as C++ one. scanf & printf are C functions, as much as your includes stdio.h & stdlib.h & math.h. In c++ you have the include iostream, and in this case it's all you really need.
The second problem here is the way you handle the input validation when it wrong. exit is very dangerous way, and very not recommended. If you want to throw exception use throw method (Read about the difference between the two: https://stackoverflow.com/a/56406586/8038186). But, in this case I don't understand why do you need to throw exception at all. you can simply finish the program in more gentle way. Consider the following flow:
#include <iostream>
using namespace std;
// Num is moved by reference and not by pointer
bool input(int &num) { // return true if the input is good, otherwise return false.
cout << "Please enter number: " << endl; // Tell the user that he should enter a number.
cin << num;
bool is_valid = num >= 1 && num <= 1e5; // 1e5 = 100000
if (!is_valid) cout << "Invalid input." << endl;
return is_valid;
}
int main() {
int n;
if (!input(n)) {
return 0;
}
int a[n];
int i;
for (i = 0; i < n && input(a[i]); i++);
if (i < n) {
return 0;
}
for (i = 0; i < n; i++) {
// The following if is useless, the validation make sure already that all of the numbers are legal.
//if (a[a[i]] >= 0) { // You don't need abs(a[i]), a[i] > 1
if (a[i] < n)
a[a[i]] = -a[a[i]];
else cout << "Consider what do you want to do" << endl;
/*} else {
printf("%d", a[i]);
return 0;
}*/
}
return 0;
}
Read about the difference between reference and pointer: What are the differences between a pointer variable and a reference variable in C++?

I'm trying to use something other than a boolean function

P is one-dimensional array of integers. Write a C++ function to efficiently search for a data VAL from P. If VAL is present in the array then the function should return the position of the value otherwise display the value doesn’t exist.
#include<iostream>
using namespace std;
bool lsearch(int Arr[], int s, int VAL);
int main()
{
int Arr[100],n,val;
bool found;
cout<<"Enter number of elements you want to insert ";
cin>>n;
for(int i=0;i<n;i++)
{
cout<<"Enter element "<<i+1<<":";
cin>>Arr[i];
}
cout<<"Enter the number you want to search ";
cin>>val;
found=lsearch(Arr,n,val);
if(found)
cout<<"\nItem found";
else
cout<<"\nItem not found";
return 0;
}
bool lsearch(int Arr[], int s, int VAL)
{
for(int I=0; I<s; I++)
{
if(Arr[I]==VAL)
return true;
}
return false;
}
I'm asked to use something other than boolean like void found: i tried void with return at end but it does not work
Your requirement is to return the position.so, you can do in the below way.
int lsearch(int Arr[], int s, int VAL)
{
for(int I=0; I<s; I++)
{
if(Arr[I]==VAL)
return I;
}
return -1;
}
You're supposed to return the position of the value, so bool and void are both the wrong choice - it should be an integer of some sort.
Since the position must be a non-negative integer, you can return a signed integer and indicate failure by returning a negative number. (-1 is the "normal" choice, so choose that.)
Then you make the output depend on whether the result is negative or not.
The relevant part of your main would look like
int position = lsearch(Arr,n,val);
if (position >= 0)
{
cout << "Item found at position " << position << endl;
}
else
{
cout << "Item not found" << endl;
}

Finding number of occurence of a given number in an array

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.

Why segmentation fault occurs in further iterations of brute force

I am trying to solve a puzzle again! this is the link: http://www.puzzleup.com/2015/puzzle/?9
my method requires vectors. Because I use this method:
I valued all the corners, and I track each iteration thrugh the end(15 th corner). I start from 1 and record all the corners I ve been through in the possibilities 2d array.
#include <iostream>
#include <vector>
#include <cmath>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
/*
possibilities will keep the possible combinations, routes like {1,4}{4,8}{8,7} etc till it arrives to 15
*/
vector< vector<int> > possibilities;
int cubes[15][6] = { {2,3,5,0,0,0}, {1,4,6,0,0,0}, {1,4,7,0,0,0}, {2,3,8,0,0,0}, {1,6,7,0,0,0}, {2,5,8,0,0,0}, {3,5,8,0,0,0}, {4,6,7,9,10,13}, {8,11,12,0,0,0}, {8,11,14,0,0,0}, {9,10,15,0,0,0}, {9,13,15,0,0,0}, {8,12,14,0,0,0}, {10,13,15,0,0,0}, {11,12,14,0,0,0} };
int counterSet, i, j, temp, counter, sizeOfVec ;
int routeCheck(int a, int b)
{
//
if(possibilities.size()!=0)
{
//
sizeOfVec = 0 ;
for(i=0; i<possibilities.size(); i++)
{
//
sizeOfVec += possibilities[i].size();
}
if(sizeOfVec!=0)
{
//
for(i=0; i< sizeOfVec; i++)
{
//
if((possibilities[i][0] == a && possibilities[i][1] == b) || (possibilities[i][0] == b && possibilities[i][1] == a))
{
//
return 0;
}
}
return 1;
}
else
{
//
return 1;
}
}
else
{
//
return 1;
}
}
int routeKeeper(int a, int b)
{
//
if(routeCheck(a,b) == 0)
{
//
return 0;
}
else if(routeCheck(a,b) == 1)
{
//
possibilities.push_back({a,b});
}
}
void createRouteMap(int start, int end)
{
//
temp = j;
for(j=0; j<6; j++)
{
//
cout << j << endl;
if(cubes[start-1][j]==0)
{
//
}
else if(cubes[start-1][j]==end) // if it is destination
{
//
counter+=1;
cout << "counter is: " <<counter << endl;
}
else if(routeCheck(start, cubes[start-1][j])==1)
{
//
routeKeeper(start, cubes[start-1][j]);
cout << "vector size is: " <<sizeOfVec << endl;
createRouteMap(cubes[start-1][j], end);
}
}
j=temp;
possibilities.erase(possibilities.end());
}
int main(int argc, char** argv) {
counter = 0;
createRouteMap(1, 15);
cout<< counter << endl;
system("pause");
return 0;
}
My all code is above shared. I use bruteforce to count all possible ways to 15 th corner. However, eventhough there is no compiling error, terminal constantly get crashed. When I execute in debug mode(I use Dev-C++ 5.11) I get this error:
Program Received signal SIGSEGV: Segmentation Fault
Of course I ve researched and found similar questions about my problem. But most of the suggestors pointed this was about the program trying to access a memory which is not belong to it. But the crazy thing is, I actually access all the memory, you can try in any editor, it runs first 3 iterations and use all the functions and variables. Output is like this:
Why is this happening? I would apreciate any suggestion and direction. Thanks.
This part of code seems strange.
sizeOfVec = 0 ;
for(i=0; i<possibilities.size(); i++)
{
//
sizeOfVec += possibilities[i].size();
}
if(sizeOfVec!=0)
{
//
for(i=0; i< sizeOfVec; i++)
{
//
if((possibilities[i][0]
sizeOfVec is used to index the vector possibilities but it count the total size of the vectors which are possibilities elements.
Many would suggest you to use a debugger for this.