+ 1

Can anyone tell why two random numbers are being generated automatically?

Two random no r being generated automatically at last. Help please https://code.sololearn.com/cH5AYhydcCzf/?ref=app

12th Feb 2022, 2:56 PM
Raisun Lakra
4 Respuestas
+ 6
raisun lakra Just do like this: void printArrayElement(int a[], int i, int n) { if (i < n) { printf(" %d", a[i]); printArrayElement(a, ++i, n); } } no need to do any other thing
12th Feb 2022, 3:27 PM
A͢J
A͢J - avatar
+ 4
raisun lakra Because after printing last element i would be increase and garbage value will be print. For example if element is 5 then i would be 5 but a[5] is nothing in the array so garbage value will come https://code.sololearn.com/c6ko0WpHWkqT/?ref=app
12th Feb 2022, 3:06 PM
A͢J
A͢J - avatar
+ 4
The function printArrayElement() keeps printing until it finds a zero in memory. Unless you deliberately place a zero in the last element, it may keep printing past the end of the array until there happens to be a zero somewhere in memory. A quick fix to make this work would be to allocate one more element to the array size and assign a zero there. int a[n+1]; //add one more element printf("\nInput %d element in the array :",n); for(int i=0;i<n;i++){ printf("\nElement - %d : ",i); scanf("%d",&a[i]); } a[n] = 0; //force a terminating zero
12th Feb 2022, 3:08 PM
Brian
Brian - avatar
+ 3
C does not automatically initialize local arrays with zero. After array declaration of n elements, the array is addressed by indices 0 through n-1. If you access arr[n] or arr[n+1] then it is outside the array boundary. The two extra values that you see are the next two values that are found in memory past the end of the array.
12th Feb 2022, 3:34 PM
Brian
Brian - avatar