void PrintArray(int arr[],int size)
{
static int i=0;
if(i==size) {
return;
}
cout<<arr[i]<< " ";
i++;
PrintArray(arr,size);
}
I'm trying to print an array using recursive function .In this solution , i can't understand how the static int i variable works. Every iteration the recursion function call itself so value of i variable was to have 0 for every recursive call .How this is work ?
I try to print an array.
Related
This question already has an answer here:
Variable changed in function not seen by caller?
(1 answer)
Closed 6 years ago.
My code is about implementing the function of Stack and Queue. If you're wondering why don't I use struct in my program that's because our instructor only allows us to use pointers and I'm a little bit confused using pointers. It's not yet finish, as much as possible I try to finish one function at a time instead of skipping to the next.
#include <stdio.h>
int container[5];
int len=0;
As I understand this part of my in function insert, "len" is suppose to change since it's incremented every time the function is use
int insert(int container[],int len)
{
int i,j,content,*incre;
incre=&len;
for(i=*incre;i<*incre+1;i++)
{
printf("Enter number:\n");
scanf("%d",&content);
container[i]=content;
}
(*incre)++;
}
int printcontent(int container[])
{
int i;
printf("Content of container:\n");
for(i=0;i<len+1;i++)
{
printf("%d ",container[i]);
}
printf("\n");
}
This part asks the user whether to add a content in the container or simply remove it. They can only add or remove one at a time.
int stack(int container[])
{
while(1)
{
int choice;
printf("What do you wanna do?\n");
printf("1.Insert\n2.Pop\n3.isEmpty\n4.Exit\n");
scanf("%d", &choice);
I checked the value of len it remains 0 instead of 1 when I first use insert.
if (choice==1)
{
insert(container,len);
printf("Value of len:%d\n",len);
printcontent(container);
}
else if(choice==4)
{
break;
}
}
}
main()
{
while(1)
{
int choice;
printf("What do you want to do?\n");
printf("1.Stack\n2.Queue\n3.Exit\n");
scanf("%d",&choice);
if(choice==1)
{.
stack(container);
}
else if(choice==3)
{
break;
}
}
}
Thanks for all of your help.
What your insert(...) function does is that it takes the parameter int len by value. That means if you call insert(...) with the local variable len as an argument in main(...) or whereever - it actually copies the value of the local variable len to the argument variable len inside the insert(...) function. The variable len which is inside the insert(...) function is then local to the insert function. That does not change even if you're declaring a pointer named incre pointing to this insert(...)-local variable len.
Then the argument variable len is incremented - but due to the fact that it is a local variable of the insert(...) function you will not see the original local variable len (which is in main(...) e.g.) being changed.
If you want to pass the original len by reference instead of by value, you have to declare your function like this ...
int insert(int container[], int* len) { ... } // Using raw pointers
... or like this ...
int insert(int container[], int& len) { ... } // Using references
... and use it like that (depending on the decision above):
insert(container, &len); // With pointers
insert(container, len); // With references
I am trying a write a program that prints a pyramid by calling a function (pass by value and not pass by address).
Well, the function is just supposed to run a for loop to print the pyramid but the actual printing statement is written in the main. The rest of the program seems fine but there is an error in the function call.
Can you please tell me what I am doing wrong? It is the syntax that I am having trouble with. The error is "argument of type void is incompatible with parameter type of 'constant char*'"
#include<stdio.h>
void pyramid(int); //function declaration
int main()
{
int r1;
printf("Enter the number of rows you would like printed:");
scanf("%d",&r1);
printf(pyramid(r1)); //function call
return 0;
}
void pyramid(int r2) //function definition
{
int i,j;
for(i=r2;i>=1;i--)
{
for(j=r2;j<=i;j--)
{
printf("*");
}
printf("\n");
}
}
void pyramid(int); //function declaration
Here the function pyramid will not return any value,
But you are expecting it to return a value in the below statement
printf(pyramid(r1)); //function call
Also this program would run in to an infinite loop,
Here:
for(i=r2;i>=1;i--)
{
for(j=r2;j<=i;j--) //**j will always be less than i**
{
printf("*");
}
printf("\n");
}
printf's prototype is
int printf(const char *restrict format, ...);
But you are trying to pass void to it by calling printf(pyramid(r1));. Call function directly like pyramid(r1); instead of printf(pyramid(r1));.
Taking this as an example:
bool SolveSudoku(int grid[N][N])
{
int row, col;
// If there is no unassigned location, we are done
if (!FindUnassignedLocation(grid, row, col))
return true; // success!
// consider digits 1 to 9
for (int num = 1; num <= 9; num++)
{
// if looks promising
if (isSafe(grid, row, col, num))
{
// make tentative assignment
grid[row][col] = num;
// return, if success, yay!
if (SolveSudoku(grid))
return true;
// failure, unmake & try again
grid[row][col] = UNASSIGNED;
}
}
return false; // this triggers backtracking
}
The grid is always passed as a parameter to the recursive call, so there is a new copy of the grid in each iteration.
I can't seem to conceptualize if there is any difference on working with a global grid, using the same logic.
After a failure condition, the variable is set to "unmake & try again"- shouldn't this take care of any "undoing" in backtracking?
What difference would there be in this recursive backtracking if the grid was a global, why send and extra copy each time?
The grid is always passed as a parameter to the recursive call, so
there is a new copy of the grid in each iteration.
No, there is a new copy of the reference (pointer) to the grid in each iteration. The actual work is done on the same grid over and over.
Have a look at this code snap for example:
#include <stdlib.h>
#include <stdio.h>
void foo(int arr[], int n) {
arr[0] = 1;
}
int main() {
int myArray[5] = {0,0,0,0,0};
foo(myArray,5);
printf("%d",myArray[0]);
return 0;
}
Note that no copy was made, and a change to arr in foo() was reflected to myArray.
Once this is clear, I believe it automatically answers the rest of your questions (It is basically the same as working with global, but global variables are usually bad practice, sending the reference to the array is a better practice).
In C/C++ arrays are passed as pointers to the beginning of array. Take a look at this example:
#include <iostream>
static const int N = 10;
void test(int a[N][N])
{
std::cout << a << std::endl;
}
int main(int argc, char **argv)
{
int a[N][N];
std::cout << a << std::endl;
test(a);
return 0;
}
If you run it you will get the same value printed on stdout:
$ ./test
0x7fff0c669930
0x7fff0c669930
That's the value of a pointer to the beginning of the array, so the same pointer is used in main() and test().
This means you would not get any performance gain by letting the grid be a global variable. Instead you would loose modularity by introducing a global.
i made a simple sorting program in which i initialized array like below.
int a[]={9,4,7,8,5,2,6,1,0,3};
but my sorting function sorts array a[0] to a[7] and treats 0 like '\0' and stops. if i put 0 at some other place it is sorting just up to 0 and ignores rest of the array. Is C is treating 0 and '\0' same here?
My Bubble Sort Program is as below.
#include<stdio.h>
#include<conio.h>
int main()
{
int a[]={9,4,7,8,5,2,6,1,0,3};
void bubble_sort(int *a);
void print(int *a);
bubble_sort(a);
print(a);
getch();
return 0;
}
void bubble_sort(int *a)
{
int i=0,j,t,n;
for(i=0;a[i]!='\0';i++)
{
n=0;
for(j=1;a[j]!='\0';j++)
{
if(a[j-1]>a[j])
{
t=a[j-1];
a[j-1]=a[j];
a[j]=t;
n++;
}
}
if(n==0)
{
break;
}
}
}
void print(int a[])
{
int i=0;
for(i=0;a[i]!='\0';i++)
{
printf("%d ",a[i]);
}
printf("\n");
}
'\0' is 0 by definition. You need to pass the length of your array to your sorting function, or else choose a different integer value as a terminator and make sure you never use that value for anything else.
The character '\0' is exactly equal to 0. You will want to pass an array length into your sorting algorithm, then use that.
'\0' is NULL character.ASCII code of NULL Character is 0.
a[i]!='\0' is equivalent to a[i]!=0
since '\0' is type casted to its ASCII value(Integer).
Thus the loop stops when ever current element is zero.
In order to fix it,pass an extra argument : array size
bubble_sort(a,sizeof(a)/sizeof(int));
print(a,sizeof(a)/sizeof(int));
Change the bubble_sort function to:
void bubble_sort(int *a,int sz)
{
int i=0,j,t,n;
for(i=0;i<sz;i++)
{
n=0;
for(j=1;j<sz;j++)
{
...................................
Change the print function to:
void print(int a[],int sz)
{
int i=0;
for(i=0;i<sz;i++)
{
.......................
Please note:
in C++ it is nearly impossible to calculate the size of array from decaying pointer(int *a or int a[]).
Therefore, always an extra argument : size of array is passed along with array.
However, whenever character array is passed to a function, simply iterating the array until NULL character is encountered works as in C/C++, a string of characters is stored in successive elements of a character array and terminated by the NULL character.
Is C is treating 0 and '\0' same here?
Yes. It's because both are zero. As others mentioned,or you pass the length of your array to function or use chose another delimiter for your array where you need to ensure that it will not contains in your array.
EDIT: #Jim Balter,thanks for clarification.
I am trying to implement INSERTION SORT here in C, which I think I've done successfully. However, I am having problems in passing arrays as arguments.
I want in place sorting, which means that the original array passed into the insertion_sort function should contain the elements in the sorted array itself.
#include<stdio.h>
int * insertion_sort(int *a,int length)
{
int j;
for(j=1;j<length;j++)
{
int i,key=a[j];
for(i=j-1;j>=0;j--)
{
if(a[i]<=key)
break;
a[i+1]=a[i];
}
a[i+1]=key;
}
return *a;
}
int main(void)
{
int a[]={10,12,7,6,9,8};
insertion_sort(a,6);
int i;
for(i=0; i<6; i++)
printf("%d\n", a[i]);
return 0;
}
EDIT
Nothing gets printed in the output screen.
Help me find the bug here. Thanks !!
1.You probably meant to use i in the inner loop:
Change:
for(i=j-1;j>=0;j--)
^^ ^^
to:
for(i=j-1;i>=0;i--)
2.You don't have to return anything as the original array gets modified (which is just as well since you ignore the returned value).
3.Array index starts from 0. Change outer loop to: for(j=0;j<length;j++)