Follow us Likes Follows us

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Thread Contributor: adminCoding [NYU Bridge program] Recursive webinar
#1
Code:
// Example program
#include <iostream>
#include <string>
using namespace std;
int sumArray(int* arr, int arrSize)
{
   // int resSum;
   // if(arrSize == 1)
   // {
   //   return arr[0];
   // }
   
   // else
   // {
   //     resSum = sumArray( arr + 1, arrSize - 1);
   //     resSum = resSum + arr[0];
   //     return resSum;
   // }
   
   
   
   
   // int resSum ;
   // if(arrSize == 1)
   // {
   //   return arr[0];
   // }
   // else
   // {
   //   resSum = sumArray(arr, arrSize - 1);
   //   resSum += arr[arrSize - 1];
   //   return resSum;
   // }
   

 
}

int main()
{
   int arr[5] = { 1, 2, 3, 4 ,5};
   int sum = sumArray(arr,5);
   cout << sum;
}

We have been talked a lot about recursive!
Everyday is the 1st day of your life!
So make it beautiful!
Heart
Reply
#2
// Example program
#include <iostream>
#include <string>
using namespace std;
void reverseArray(int* arr, int arrSize)
{
int last;
if(arrSize == 1)
{
return;
}
else
{
reverseArray (arr, arrSize - 1);
last = arr[arrSize -1];
for(int i = arrSize - 2; i >= 0; i-- )
{
arr[i + 1] = arr[i];
}
arr[0] = last;
}

}

void printArray(int arr[], int arrSize)
{
for(int i = 0 ; i< arrSize; i++)
{
cout << arr[i] << " ";
}
}
int main()
{
int arr[5] = { 1, 2, 3, 4 ,5};
reverseArray(arr, 5);
printArray(arr, 5);



}
Everyday is the 1st day of your life!
So make it beautiful!
Heart
Reply
#3
// Swap the last and the 1st same time
#include <iostream>
#include <string>
using namespace std;
void reverseArray(int* arr, int arrSize)
{
//swap ( first with last then recursive the rest).
if(arrSize == 1)
{
return;
}
else
{
reverseArray(arr + 1, arrSize -2);
int temp = arr[0];
arr[0] = arr[arrSize - 1];
arr[arrSize - 1] = temp;
}

}

void printArray(int arr[], int arrSize)
{
for(int i = 0 ; i< arrSize; i++)
{
cout << arr[i] << " ";
}
}
int main()
{
int arr[5] = { 1, 2, 3, 4 ,8};
reverseArray(arr, 5);
printArray(arr, 5);



}
Everyday is the 1st day of your life!
So make it beautiful!
Heart
Reply
#4
// Example 4
#include <iostream>
#include <string>
using namespace std;
void reverseArray(int* arr, int arrSize)
{
//swap ( first with last then recursive the rest).
if(arrSize == 1)
{
return;
}
else
{
reverseArray(arr + 1, arrSize -2);
int temp = arr[0];
arr[0] = arr[arrSize - 1];
arr[arrSize - 1] = temp;
}

}

void printArray(int arr[], int arrSize)
{
for(int i = 0 ; i< arrSize; i++)
{
cout << arr[i] << " ";
}
}
int main()
{
int arr[5] = { 1, 2, 3, 4 ,8};
reverseArray(arr, 5);
printArray(arr, 5);



}
Everyday is the 1st day of your life!
So make it beautiful!
Heart
Reply




Users browsing this thread: 1 Guest(s)