I am declaring an array inside main() and without initializing the array, I am printing the array by passing it to a function. It is printing the same value as many time as I run this program.
As we know after declaring an array, it is initialized with random values. Then how it can print 1,2,3,4,5,......
for all the time.
void print(int ar[],int n){ for(int i=0;i<n;i++) cout<<ar[I]<<""; cout<<endl;}
OUTPUT :0 1 2 3 4
When I am printing array inside main() using a for loop, then I got random values.
int main(){ int ar[5]={0}; for(int i=0;i<5;i++) cout<<ar[i]<<"";}
OUTPUT :-2 6422280 1978757101 4201168 6422352
But, when I am making change to this array inside function, then it is not reflecting change outside that function.
#include<bits/stdc++.h>using namespace std;void flush(int ar[],int n){ for(int i=0;i<n;i++) ar[i]=0;}void setar(int ar[],int n){ for(int i=0;i<n;i++) ar[i]=1;}void print(int ar[],int n){ for(int i=0;i<n;i++) cout<<ar[i]<<""; cout<<endl;}int main(){ int ar[5]={0}; flush(ar,5); print(ar,5); setar(ar,5); print(ar,5);}
As we know array is passed by reference, so change made inside function, should be visible outside function also. SYSTEM :Windows 10
gcc compiler
VSCode studio
C++ 14