How to traverse a 2D array using recursion - c

I'm looking for someone to help me to traverse and display the 2d array or matrix using recursion.
void display(int** matrix1,int row, int column)
This is what I am doing for the 1D array:
void print_array(int arr[], int size, int i)
{
if (i == size) {
cout << endl;
return;
}
cout << arr[i] << " ";
print_array(arr, size, i+1);
}
I know how to traverse 1D array but unable to do this.
I want to display each element in the matrix using recursion.

First of all, it is not quite clear why you want a recursive solution. Perhaps it is a matter of tase, but I find recursion difficult to write, read and debug. Anyhow, I allowed myself to modify your 1d version:
#include <iostream>
#include <vector>
void print_array(const std::vector<int>& arr,size_t i = 0) {
if (i == arr.size()) {
std::cout << '\n';
return;
}
std::cout << arr[i] << " ";
print_array(arr, i+1);
}
I use size_t instead of int, because thats the type to be used when comparing with a containers size. I supplied a default for i because when you call it you dont want to pass the index, but just print the whole array. std::endl is not only printing a new line, but it also flushes the stream. This is unnecessary in most cases.
For the 2D case all you need to add is a second index and a condition to go to the next row.
That is, if the signature of the function is
void print_array(const std::vector<std::vector<int>>& arr,size_t i=0,size_t j=0)
and it prints arr[i][j] then you need to return without printing anything when i == arr.size() and you have to skip to the next row when j== arr[i].size(). This can be done with a condition along the line of:
if (j == arr[i].size()) {
std::cout << '\n';
print_array( arr, i+1,0); // start with the first element of next row
return;
}
PS is you insist on a int**, it should be straightforward to adapt, but I would strongly suggest to use a vector and perhaps even a std::vector<std::array> if the inner arrays all have same size.

I am sure that you need to write a C program or a C++ program but using functionality of C due to your declaration of "2D array" like int **.:)
The function can be easy implemented if to use one more auxiliary recursive function.
Here is a demonstrative program
#include <stdio.h>
void display_row( int *a, size_t column )
{
column == 0 ? ( void )putchar( '\n' )
: ( void )( printf( "%2d ", *a ), display_row ( ++a, --column ) );
}
void display( int **a, size_t row, size_t column )
{
if ( row != 0 )
{
display_row( *a, column );
display( ++a, --row, column );
}
}
int main(void)
{
enum { M = 3, N = 4 };
int a1[N] = { 1, 2, 3, 4 };
int a2[N] = { 5, 6, 7, 8 };
int a3[N] = { 9, 10, 11, 12 };
int *a[M] = { a1, a2, a3 };
display( a, M, N );
return 0;
}
The program output is
1 2 3 4
5 6 7 8
9 10 11 12
If not to use an auxiliary function then another approach is to use a static variable inside the recursive function.
Here is a demonstrative program that uses a recursive function with a static variable.
#include <stdio.h>
void display( int** a, size_t row, size_t column )
{
static size_t pos = 0;
if ( row != 0 && column == 0 )
{
putchar( '\n' );
size_t tmp = column;
column = pos;
pos = tmp;
--row;
++a;
}
if ( row )
{
printf( "%2d ", a[0][pos++] );
display( a, row, --column );
}
}
int main(void)
{
enum { M = 3, N = 4 };
int a1[N] = { 1, 2, 3, 4 };
int a2[N] = { 5, 6, 7, 8 };
int a3[N] = { 9, 10, 11, 12 };
int *a[M] = { a1, a2, a3 };
display( a, M, N );
return 0;
}
Its output is the same as shown above.
If you need a C++ program then just include headers
#include <iostream>
#include <iomanip>
and instead of for example this call of printf
printf( "%2d ", a[0][pos++] );
use
std::cout << std::setw( 2 ) << a[0][pos++];

Here is a simple recursive solution hope you can understand............
#include <iostream>
using namespace std;
void print(int x,int y,int arr[3][3])
{
cout<<arr[x][y]<<" ";
if(x==2 && y==2)//Its a 3 by 3 matrix.....Index starts from 0 and ends at 2 for both row and colomn.
{
return;
}
else if(y==2)
{
cout<<endl;
print(x+1,0,arr);
}
else
print(x,y+1,arr);
}
int main()
{
int arr[3][3]={{1,2,3},{4,5,6},{7,8,9}};
print(0,0,arr);
return 0;
}

Related

What error did i make writing my recursive function using arrays?

#include <stdio.h>
#include <math.h>
int prod(int arr[], int n) {
if (arr[n-1] < 0) {
return 1;
}
return ((arr[n-1]) * (prod(arr[n-2] , n)));
}
int main( int argc, char* args[] ) {
int arr[] = {2 , 3};
printf("%d" , prod(arr , 2));
}
i keep getting pointer related errors but have no idea what to change, any help? The code is supposed to use the recursive function to get the product of all integers equal or over 0 in the array.
I guess the condition for termination of recursion should be:
if (n-1 < 0) {
return 1;
}
It can be reformulated as:
if (n <= 0) {
return 1;
}
What means that product of entries of empty array is 1.
Moreover, expression that goes deeper should be:
return arr[n-1] * prod(arr , n - 1);
The final code could be:
int prod(int arr[], int n) {
if (n == 0)
return 1;
return arr[n-1] * prod(arr, n - 1);
}
There should be assignment in the prod function with something like this:-
n=n-1
You are not decreasing the value of n anywhere.
This function is incorrect.
int prod(int arr[], int n) {
if (arr[n-1] < 0) {
return 1;
}
return ((arr[n-1]) * (prod(arr[n-2] , n)));
}
For starters this if statement
if (arr[n-1] < 0) {
return 1;
}
does not make a sense.
It seems you mean
if ( n-1 < 0) {
return 1;
}
In this expression
prod(arr[n-2] , n)
the first argument is a scalar object of the type int. That is arr[n-2] is an element of an array. Also the second argument shall be decremented that is you have to use the expression n - 1.
But apart from this there are several other drawbacks.
For starters a product of elements of an array can be too big to fit in an object of the type int, You should use at least the type long long int as the return function type or maybe the float type long double.
Secondly as the array is not being changed within the function then the first parameter should have the qualifier const.
The user can pass as second argument the value 0. In this case it will look strange that the function returns 1.
Thus the function should look at least like
long long int prod( const int arr[], size_t n )
{
return n == 0 ? 0 : ( n == 1 ? arr[n-1] : arr[n-1] * prod( arr, n - 1 ) );
}
Here is a demonstrative program
#include <stdio.h>
long long int prod( const int arr[], size_t n )
{
return n == 0 ? 0 : ( n == 1 ? arr[n-1] : arr[n-1] * prod( arr, n - 1 ) );
}
int main(void)
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
printf( "%lld\n" , prod( arr , sizeof( arr ) / sizeof( *arr ) ) );
return 0;
}
The program output is
3628800

How to edit an array in another function than the main function in c programming?

I'd like to increase each element in the array by one in another function than the main function. Then, I'd like to call this function and print in the main function.
#include <stdio.h>
int function(int array2[5]) {
int i;
while(i<4) {
array2[i]=array2[i]+1;
i++;
}
return array2[5];
}
int main() {
int array[5]={1,2,3,4,5};
int answer;
answer[5]=function(array[5]);
int j;
while(j<4) {
printf("%d \n",answer[j]);
j++;
}
return 0;
}
Some important things to know:
When you pass an array in C, you don't make a copy. It is the same array, so modifying the array that is passed in modifies the original.
The [] are operators and not part of the variable name.
The [] work differently in declaring a type than when used in an expression. array[5] gives you the 6th element in array, but int array[5] declares an array with 5 elements.
Accessing an element beyond the end of the allocated array has undefined behavior, but usually will crash.
If you declare a variable int answer it is not an array, and cannot become an array. It is just one int
If you want to make a copy of an array, you need to explicitly copy. There are standard libraries that might do it, but you should learn to copy each element, one by one, to the new array.
The return type int of the function does not make a sense.
int function(int array2[5]) {
And moreover you are trying to return the non-existent 6-th element of an array with only 5 elements.
return array2[5];
Within the function you are using uninitialized variable i
int function(int array2[5]) {
int i;
while(i<4) {
//...
that results in undefined behavior. Also the used magic number 4 does not make a sense at least because you are trying to pass to the function an array with 5 elements.
The function should be declared with a second parameter that specifiers the number of elements in the passed array. This function declaration
int function(int array2[5]);
does not mean that the passed to the function array has exactly 5 elements. The compiler will adjust the parameter declaration of the function to pointer to the array element type like
int function(int *array2);
In this statement in main
int answer;
answer[5]=function(array[5]);
you are using the subscript operator with an object of the scalar type int. So the compiler shall issue an error message.
Here is a demonstrative program that shows how the function can be defined.
#include <stdio.h>
void function( int a[], size_t n )
{
for ( ; n--; ++a )
{
++*a;
}
}
int main(void)
{
int a[] = { 1, 2, 3, 4, 5 };
const size_t N = sizeof( a ) / sizeof( *a );
for ( size_t i = 0; i < N; i++ )
{
printf( "%d ", a[i] );
}
putchar( '\n' );
function( a, N );
for ( size_t i = 0; i < N; i++ )
{
printf( "%d ", a[i] );
}
putchar( '\n' );
return 0;
}
The program output is
1 2 3 4 5
2 3 4 5 6
There you go. I suppose this is what you want:
#include <stdio.h>
// Since the array named parameters are scoped only within its function,
// they are apart from your array in the main.
void function(int array[], int len) {
int i = 0;
while(i<len) {
array[i]=array[i]+1;
i++;
}
}
// Or alternatively you can process the array using a pointer
void functionWithPointer(int *array, int len) {
int i = 0;
while(i<len) {
*(array+i) = *(array+i)+1;
i++;
}
}
int main() {
int array[]={1,2,3,4,5};
// int answer; // Not necessary
int length = sizeof(array) / sizeof(int); // !!!ATTENTION
function(array, length);
// The array values updated by 1
printf("Array values after 1st update\n");
for(int k=0; k<length; k++) {
printf("%d \n",array[k]);
}
functionWithPointer(array, length);
// The array values updated by 1 again
printf("Array values after 2nd update\n");
int j;
while(j<length) {
printf("%d \n",array[j]);
j++;
}
return 0;
}
Here is the output:
Array values after 1st update
2
3
4
5
6
Array values after 2nd update
3
4
5
6
7

How to perform A-B set operation in C program using builtin library

I am new to C language. Suppose I have two arrays a and b
int a[10] = { 1,2,3,4,5,6,7,8,9,0 };
int b[10] = { 1,3,5,7,9 };
and I want to perform a-b so that I can get all elements of array a which are not present in array b. In ruby or python, I can just simply do a-b and get the result. Here is my c code that I have tried but my code which is not working.I am looking for a C library that does this operation for me in a line.I have also found this library but not sure how to implement it. Any kind of help is appreciated.
#include<stdio.h>
#define Max 100
int m,n,i,j,k,p,q,r,s;
int flag=1;
char char1,char2,char3;
void Difference(int *,int *,int ,int);
void Display2(char ,char ,int );
int a[10] = { 1,2,3,4,5,6,7,8,9,0 };
int b[10] = { 1,3,5,7,9 };
int c[10];
void Difference(int *a1,int *b1,int m1,int n1)
{
q=0;
p=0;
i=0;
for(k=0;k<m1;k++){
flag=1;
for(j=0;j<n1;j++){
if(b1[j]==a1[k]){
flag=1;
q++;
break;
}
else{
flag=0;
}
}
if(flag==0){
c[p]=a1[k];
p++;
}
}
}
void Display2(char ac,char bc,int m1)
{
printf("\nThe Difference Of Two Sets i.e '%c - %c' Is : { ",ac,bc);
r = m1 - q;
for(p=0;p<r;p++){
printf("%2d",c[p]);
}
printf(" }");
}
int main(){
Difference(a,b,m,n);
Display2('A','B',m);
return 0;
}
I can guess, you forgot to initialize your m and n variables with proper values.
Add m = 10; n = 5; before calling Difference and your code will work.
I also suggest you to write more readable code: better naming for variables, use some spaces and avoid global variables.
Edit:
In C++ you can write:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <set>
int main() {
std::set<int> a = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
std::set<int> b = { 1, 3, 5, 7, 9 };
std::set<int> c;
std::set_difference(a.begin(), a.end(), b.begin(), b.end(), std::inserter(c, c.begin()));
for (const auto item : c)
std::cout << item << " ";
return 0;
}
Detail information about std::set_difference can be found here

Find array index if given value

I want to retrieve the index in the array where the value is stored. I know the value of the item at that point in the array. I'm thinking it's similar to the findIndex function in c#.
For example, array[2] = {4, 7, 8}. I know the value is 7, how do I get the value of the index, 1, if I know it is at array[1]?
For example you can define the corresponding function the following way
size_t FindIndex( const int a[], size_t size, int value )
{
size_t index = 0;
while ( index < size && a[index] != value ) ++index;
return ( index == size ? -1 : index );
}
Also instead of type size_t you can use type int.
But the better way is to use standard algorithm std::find or std::find_if declared in header <algorithm> provided that you use C++
For example
#include <algorithm>
#include <iterator>
int main()
{
int a[] = { 4, 7, 8 };
auto it = std::find( std::begin( a ), std::end( a ), 7 );
if ( it != std::end( a ) )
{
std::cout << "The index of the element with value 7 is "
<< std::distance( std::begin( a ), it )
<< std::endl;
}
}
The output is
The index of the element with value 7 is 1
Otherwise you have to write the function yourself as I showed abve.:)
If the array is sorted you can use standard C function bsearch declared in header <stdlib.h>
For example
#include <stdio.h>
#include <stdlib.h>
int cmp( const void *lhs, const void *rhs )
{
if ( *( const int * )lhs < *( const int * )rhs ) return -1;
else if ( *( const int * )rhs < *( const int * )lhs ) return 1;
else return 0;
}
int main()
{
int a[] = { 4, 7, 8 };
int x = 7;
int *p = ( int * )bsearch( &x, a, 3, sizeof( int ), cmp );
if ( p != NULL ) printf( "%d\n", p - a );
return 0;
}
First its important that the argument list contain size information for the array, i.e. passing a pointer to an array only does not provide enough information to know how many elements the array has. The argument decays into a pointer type with no size information to the function.
So given that, you could do something like this:
int findIndex(int *array, size_t size, int target)
{
int i=0;
while((i<size) && (array[i] != target)) i++;
return (i<size) ? (i) : (-1);
}
For small arrays this approach will be fine. For very large arrays, some sorting and a binary search would improve performance
Here's my version without a additional variable.
// Return index of element starting
// Return -1 if element is not present
int indexOf(const int elm, const int *ar, int ar_cnt)
{
// decreasing array count till it reaches negative
// arr_cnt - 1 to 0
while (ar_cnt--)
{
// Return array index if current element equals provided element
if (ar[ar_cnt] == elm)
return ar_cnt;
}
// Element not present
return -1; // Should never reaches this point
}
Hope the comments are self explanatory!

Listing Arrays in C

I'm learning C . I want to list an array's values.
In PHP :
$arr = array("laguna", "megane", "clio");
foreach($arr as $no => $name)
{
echo $no." ) ".$name;
}
/*
Output :
0) Laguna
1) Megane
2) Clio
*/
How can i do it in C?
In C
char* arr[] = {"laguna","megane","clio",NULL};
for( int i = 0; arr[i]; i++)
{
printf("%d) %s\n",i,arr[i]);
}
NOTE: The OP's question was originally tagged as C++, so I'll leave this answer as-is for those who might be curious about a C++ specific method
You can use the for_each algorithm inside of algorithm ... it works with any object that can be dereferenced and incrementally interated (i.e., supports operator++).
The input arguments to the for_each algorithm are a pointer (or iterator) that points to the start of the array or container object if you're using STL containers like std::vector, etc., a pointer or iterator that points to one past the end of the object, and then a function that will be applied to each member of the array or container.
For instance:
#include <algorithm>
#include <iostream>
using namespace std;
int array[] = { 1, 2, 3, 4, 5 };
//pointer to the start of the array
int* start = array;
//pointer to one position past the end of the array
int* end = array + sizeof(array)/sizeof(int);
//function applied to each member of the array
void function(int a)
{
static int count = 0;
cout << "Value[" << count++ << "]: " << a << endl;
}
//call the for_each algorithm
for_each(start, end, function);
#include <stdio.h>
int main(){
char *arr[] = {"laguna", "megane", "clio", NULL};
char **name = arr;
while(*name){
int no = name - arr;
printf("%d ) %s\n", no, *name++);
}
return 0;
}
C and C++ are not the same language. Using C++ std::vector in a recent C++ dialect, you might try (untested code):
std::vector<std::string> vecstr;
vecstr.push_back("laguna");
vecstr.push_back("megane");
for (std::vector<std::string>::iterator it= vecstr.begin();
it != vecstr.end(); it++)
std::out << *it << std::endl;
This will give you a good look at using arrays in c++ .
// arrays example
#include <iostream>
using namespace std;
int billy [] = {16, 2, 77, 40, 12071};
int n, result=0;
int main ()
{
for ( n=0 ; n<5 ; n++ )
{
result += billy[n];
}
cout << result;
return 0;
}
You can go one step ahead and use STL containers like set and map.
http://ideone.com/U62Q8
In c:
#include <stdio.h>
int array[6]= { 1, 2, 3, 4, 5, 6 };
void main() {
int len=sizeof(array)/sizeof(int);
int i;
for(i=0;i<len;i++)
{
printf("Elements in position :%d :%d ",i,array[i]);
}
}

Resources