Dynamic Memory in C [closed] - c

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I can't understand what doing the row
*(m[i] + sizes[i] - 1) = n;
#include <stdio.h>
#include <stdlib.h>
#define MAXSTR 100
int main()
{
int i, j, k, n;
char str[MAXSTR];
printf("Enter amount of rows: ");
fgets(str, MAXSTR, stdin);
k = atoi(str);
int* sizes = (int * ) calloc(k, sizeof(int));
int* sum = (int * ) calloc(k, sizeof(int));
int** m = (int ** ) calloc(k, sizeof(int * ));
printf("Enter matrix:\n");
for (i = 0; i < k; i++)
{
fgets(str, MAXSTR, stdin);
char* sym = str;
while (1)
{
m[i] = (int * ) realloc(m[i], (++sizes[i]) * sizeof(int));
n = strtol(sym, & sym, 10);
sum[i] += n;
if (n)
{
*(m[i] + sizes[i] - 1) = n;
}
else
{
--sizes[i];
break;
}
}
}
printf("\nMatrix: \n");
for (i = 0; i < k; i++)
{
for (j = 0; j < sizes[i]; j++)
printf("%i ", *(m[i] + j));
printf("\n");
}
printf("\nSum of elements of row:\n");
for (i = 0; i < k; i++)
printf("#%i - %i\n", i + 1, sum[i]);
free(sizes);
free(sum);
free(m);
return 0;

m is the matrix. Or more formally, it appears to be an array of "rows". Where each row is an array of integers.
sizes[i] is the length of the row represented by m[i].
This expression
*(m[i] + sizes[i] - 1) = n;
Appears to assign the value n to the last index of the row identified by m[i]. Essentially, it's appending to the end of the reallocated array.
This entire block of code is a bit complex:
while (1)
{
m[i] = (int * ) realloc(m[i], (++sizes[i]) * sizeof(int));
n = strtol(sym, & sym, 10);
sum[i] += n;
if (n)
{
*(m[i] + sizes[i] - 1) = n;
}
else
{
--sizes[i];
break;
}
}
It could be simplified to just:
int rowsize = 0;
while (1)
{
n = strtol(sym, &sym, 10); // parse the next number in str
if (n == 0) // the row ends when 0 is read
{
break;
}
m[i] = (int *)realloc(m[i], (rowsize+1) * sizeof(int); // grow the row's size by 1
m[i][rowsize] = n;
sum[i] += n;
rowsize++;
}
sizes[i] = rowsize;

m[i] is a pointer to the first element in the i:th matrix row
sizes[i] is the current number of columns in row i
sizes[i] - 1 is the last element in row i
m[i] + sizes[i] - 1 is a pointer to the last element in row i
*(m[i] + sizes[i] - 1) is the last element in row i
When allocating memory in C the result should not be cast, so
int* sizes = (int * ) calloc(k, sizeof(int));
should be simply
int* sizes = calloc(k, sizeof(int));
Also, the rows of the matrix m are never freed; to free the entire matrix you would need
for (i = 0; i < k; i++) {
free(m[i]);
}
free(m);

To answer your question the statement *(m[i] + sizes[i] - 1) = n; assigns the value n to whatever m[i] + sizes[i] - 1 points to. m is a pointer to a pointer to an int, so m[i] is an address of an int pointer. sizes[i] - 1 is usually how you convert from a size to index, so it's an offset from that int pointer.
Here are some suggested changes (all but one implemented below):
Reduce variable scope but initialize sum to NULL before the first failure so it can be unconditionally deallocated
It is better user experience to just read the data and terminate with an empty line instead of asking for the user count upfront. Just update the count k as we go along. This eliminates atoi which does not do any error handling. If you want to crash the program due to being out of memory you have to provide the data not just large a count.
(not fixed) realloc of 1 element at a time, if the O(i^2) is a performance issue, keep track of size and capacity of sum. When size == capacity, realloc by some factor, say, 2. Optionally, realloc to size when when we finish reading data as we now have the actual number of lines k.
No point of printing the array you just entered, which means we can get rid of the m and sizes arrays
Deallocate sum if realloc fails by introducing a temporary sum2 variable that will be NULL on error, but sum will still point to previously allocated data
Check for under and overflow of n and sum
Use sizeof on variable instead of type so you can change type just one place if needed
Allow 0 values by passing in by using a separate pointer endptr than sym to strtol()
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#define CHECK(p, msg) if(!(p)) {\
printf("%s:%d %s\n", __FILE__, __LINE__, (msg));\
goto out;\
}
#define MAXSTR 100
int main() {
int k;
char str[MAXSTR];
int *sum = NULL;
printf("Enter matrix:\n");
for(int i = 0;; i++) {
fgets(str, MAXSTR, stdin);
char *sym = str;
int *sum2 = realloc(sum, (i + 1) * sizeof(*sum));
CHECK(sum2, "realloc failed");
sum = sum2;
int j;
for(j = 0;; j++) {
char *endptr;
long n = strtol(sym, &endptr, 10);
CHECK(n >= INT_MIN && n <= INT_MAX,\
"value truncated");
if(sym == endptr) {
break;
}
sym = endptr;
CHECK((n >= 0 && sum[i] <= INT_MAX - n) || \
(n < 0 && sum[i] >= INT_MIN - n),\
"sum truncated");
sum[i] += n;
}
if(!j) {
k = i;
break;
}
}
printf("Sum of elements of row:\n");
for (int i = 0; i < k; i++)
printf("#%i - %i\n", i + 1, sum[i]);
out:
free(sum);
return 0;
}
Example execution:
Enter matrix:
0 1 2
Sum of elements of row:
#1 - 3

Related

dealing with dups in end of the array

This is the task I have got:
I need to write a function (not recursive) which has two parameters.
An array of integers.
An integer representing the size of the array.
The function will move the duplicates to an end of the array.
And will give the size of the different digits.
Example:
5 , 2 , 4 , 5 , 6 , 7 , 2, n = 7
we will get back 5 , 2 , 4 , 6 , 7 , 5 , 2 and 5
We must keep the original sort as it is (which means like in example 5 must)
It does not matter how we sort the duplicates ones but just keep the sort for the original array as it is)
The function has to print the number of different digits (like in example 5)
The the input range of numbers in array [-n,n]
I can only use 1 additional array for help.
It has to be O(n)
I tried it so many times and feel like am missing something. Would appreciate any advice/suggestions.
int moveDup(int* arr, int n)
{
int* C = (int*)calloc(n * 2 + 1, sizeof(int));
assert(C);
/*int* count = C + n;*/
int *D = arr[0];
int value = 0, count = 0;
for (int i = 0; i < n; i++)
{
value = arr[i];
if (C[value + n] == 0)
{
*D = arr[i];
D++;
count++;
}
C[value + n] = C[value + n] + 1;
}
while (1 < C[value + n])
{
*D = i;
D++;
C[value + n]--;
}
free(C);
return count;
}
This algorithm will produce the required results in O(n) arithmetic complexity:
Input is an array A with n elements indexed from A0 to An−1 inclusive. For each Ai, −n ≤ Ai ≤ n.
Create an array C that can be indexed from C−n to C+n, inclusive. Initialize C to all zeros.
Define a pointer D. Initialize D to point to A0.
For 0 ≤ i < n:
If CAi=0, copy Ai to where D points and advance D one element.
Increment CAi.
Set r to the number of elements D has been advanced from A0.
For −n ≤ i ≤ +n:
While 1 < CAi:
Copy i to where D points and advance D one element.
Decrement CAi.
Release C.
Return r. A contains the required values.
A sample implementation is:
#include <stdio.h>
#include <stdlib.h>
#define NumberOf(a) (sizeof (a) / sizeof *(a))
int moveDuplicates(int Array[], int n)
{
int *memory = calloc(2*n+1, sizeof *Array);
if (!memory)
{
fprintf(stderr, "Error, unable to allocate memory.\n");
exit(EXIT_FAILURE);
}
int *count = memory + n;
int *destination = Array;
for (int i = 0; i < n; ++i)
// Count each element. If it is unique, move it to the front.
if (!count[Array[i]]++)
*destination++ = Array[i];
// Record how many unique elements were found.
int result = destination - Array;
// Append duplicates to back.
for (int i = -n; i <= n; ++i)
while (0 < --count[i])
*destination++ = i;
free(memory);
return result;
}
int main(void)
{
int Array[] = { 5, 2, 4, 5, 6, 7, 2 };
printf("There are %d different numbers.\n",
moveDuplicates(Array, NumberOf(Array)));
for (int i = 0; i < NumberOf(Array); ++i)
printf(" %d", Array[i]);
printf("\n");
}
here is the right answer, figured it out by myself.
int moveDup(int* arr, int n)
{
int* seen_before = (int*)calloc(n * 2 + 1, sizeof(int));
assert(seen_before);
int val = 0, count = 0, flag = 1;
int j = 0;
for (int i = 0; i < n; i++)
{
val = arr[i];
if (seen_before[arr[i] + n] == 0)
{
seen_before[arr[i] + n]++;
count++;
continue;
}
else if (flag)
{
j = i + 1;
flag = 0;
}
while (j < n)
{
if (seen_before[arr[j] + n] == 0)
{
count++;
seen_before[arr[j] + n]++;
swap(&arr[i], &arr[j]);
j++;
if (j == n)
{
free(seen_before);
return count;
}
break;
}
/*break;*/
j++;
if (j == n)
{
free(seen_before);
return count;
}
}
}
}
second right answer
int* mem = (int*)calloc(2 * n + 1, sizeof * arr);
assert(mem);
int* count = mem + n;
int* dest = arr;
for (i = 0; i < n; ++i)
{
if (count[arr[i]]++ == 0)
{
*dest = arr[i];
*dest++;
}
}
res = dest - arr;
for (i = -n; i <= n; ++i)
{
while (0 < --count[i])
{
*dest++ = i;
}
}
free(mem);
return res;

function that returns a version of the given arrays where each zero value in the array is replaced by the smallest odd value to the right of 0. In C

I'm having a bit of trouble with this problem. The full text of the problem is as follows : "Write a function that returns a version of the given array of non-negative integers where each zero value in the
array is replaced by the smallest odd value to the right of the zero in the array. If there is no odd value to the right of the zero,
leave the zero as a zero."
Here is my code:
#include <stdio.h>
void lowestOdd(int num[], int size) {
int i, temp;
for (i = 0; i < size; i++) {
if (num[i] % 2 != 0 && num[i] < num[i + 1]) {
temp = num[i];
}
}
for (i = 0; i < size; i++) {
if (num[i] = 0) {
num[i] = temp;
}
}
}
void printArray(int array[], int size) {
int i;
for (i = 0; i < size; i++) {
printf("%d/n", array[i]);
}
}
int main() {
int i, size;
int myarr[20];
printf("What is the size of your array? \n");
scanf("%d", &size);
for (i = 0; i < size; i++) {
scanf("%d", &myarr[i]);
}
lowestOdd(myarr[20], size);
printArray(myarr[20], size);
return 0;
}
I've tried implementing pointers in the lowestOdd function, but to no avail. I do think they're necessary here, but I'm not really that good at pointers. The warnings I get are mostly 'warning: passing argument 1 of 'lowestOdd' makes pointer from integer without a cast [-Wint-conversion]'. Also, in my code, I haven't added the statements that would check whether the number is a zero or whether there are any odd values to the right of the zero.
In the declaration
int myarr[20];
myarr is the identifier - the name used to refer to the array itself. myarr has the type int [20].
When used in this expression
lowestOdd(myarr[20], size);
[20] is the array subscript operator, accessing index 20. This is index is out of bounds, as the valid indices for the type int [20] are 0 to 19. This out of bounds access will cause Undefined Behaviour.
This warning
warning: passing argument 1 of 'lowestOdd' makes pointer from integer without a cast [-Wint-conversion]
is given because, although an invalid index to access, the expression myarr[20] evaluates to an int. lowestOdd expects an int * as its first argument.
Similar to before, in
if (num[i] % 2 != 0 && num[i] < num[i + 1])
num[i + 1] will access num[size] when i is size - 1 (again, valid indices are 0 to size - 1).
This is assignment
if (num[i] = 0)
where you want a comparison
if (num[i] == 0)
Note that
scanf("%d", &size);
for (i = 0; i < size; i++) {
scanf("%d", &myarr[i]);
risks the same out of bounds access if the user enters a value greater than 20 for size.
Ignoring the out of bounds access for a moment, lowestOdd attempts to find the last occurrence of the smaller number from each pair of numbers in the array, where the left number must be odd.
It then replaces all zeroes in the array with this value.
There is a chance temp is never assigned anything, and thus has an indeterminate value.
This is not correct.
Here is an example program (using a variable-length array).
Note that the syntax array + i is equivalent to &array[i].
? : is the conditional operator: in a ? b : c, if a is non-zero the expression evaluates to b, else it evaluates to c.
#include <stdio.h>
int min(int a, int b)
{
return a < b ? a : b;
}
int find_lowest_odd(int *base, size_t len)
{
int value = 0;
for (size_t i = 0; i < len; i++)
if (base[i] & 1) /* base[i] % 2 != 0 */
value = value ? min(value, base[i]) : base[i];
return value;
}
void mutate_array(int *a, size_t len)
{
for (size_t i = 0; i < len; i++)
if (0 == a[i]) /* search from the next position */
a[i] = find_lowest_odd(a + i + 1, len - i - 1);
}
void print_array(int *a, size_t len)
{
for (size_t i = 0; i < len; i++)
printf("%d ", a[i]);
putchar('\n');
}
int main(void) {
size_t size;
printf("What is the size of your array?: ");
if (1 != scanf("%zu", &size))
return 1;
int array[size];
for (size_t i = 0; i < size; i++) {
printf("#%zu: ", i + 1);
if (1 != scanf("%d", array + i))
return 1;
}
print_array(array, size);
mutate_array(array, size);
print_array(array, size);
}
I/O:
What is the size of your array?: 10
#1: 0
#2: 2
#3: 0
#4: 5
#5: 3
#6: 0
#7: 7
#8: 2
#9: 0
#10: 0
0 2 0 5 3 0 7 2 0 0
3 2 3 5 3 7 7 2 0 0
Once you can try this.
Here's my naive approach. For every zero in the array it is checking for the smallest odd element from that position to the last index and storing it in variable named smaller. After checking it replaces the original value of that index with smaller one.
#include<stdio.h>
void lowestOdd(int *num, int size){
int i, j;
for(i = 0; i < size - 1; i++){
if (num[i] != 0) continue;
int smaller = 99998;
for(j = i+1; j < size; j++){
if (num[j] % 2 != 0 && num[j] < smaller) smaller = num[j];
}
if (smaller != 99998) num[i] = smaller;
}
}
void printArray(int *array, int size){
int i;
for (i=0; i<size; i++){
printf("%d\n", array[i]);
}
}
int main()
{
int i, size;
int myarr[20];
printf("What is the size of your array? \n");
scanf("%d", &size);
for (i=0; i<size; i++){
scanf("%d", &myarr[i]);
}
lowestOdd(myarr, size);
printArray(myarr, size);
return 0;
}

Given an array a of n elements, print any value that appears at least three times or print -1 if there is no such value

here is my code and it always output -1 and I didn't know why. any help?
Input
The first line contains an integer t (1≤t≤104) — the number of test cases.
The first line of each test case contains an integer n (1≤n≤2⋅105) — the length of the array.
The second line of each test case contains n integers a1,a2,…,an (1≤ai≤n) — the elements of the array.
It is guaranteed that the sum of n over all test cases does not exceed 2⋅105.
Output
For each test case, print any value that appears at least three times or print -1 if there is no such value.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, size,*arr, *frr,count,*ptr,g,s;
scanf("%d", &n);
ptr = (int*)malloc(n * sizeof(int));
for (int i = 0;i < n; i++)
{
scanf("%d",&size);
arr = (int*)malloc(size * sizeof(int));
frr = (int*)malloc(size * sizeof(int));
for(int j = 0; j < size; j++)
{
scanf("%d",arr+j);
*(frr + j) = -1;
}
if(size >= 3)
{
for (g = 0; g < size ; g++)
{
count=1;
for(s = g + 1; s < size;s++)
{
if(*(arr + g) == *(arr + s))
{
count++;
*(frr+s) = 0;
}
}
if(*(frr+g) != 0 )
{
*(frr+g) = count;
}
if(*(frr+g) >= 3)
{
*(ptr+i) = *(arr + g);
}else
{
*(ptr+i) = -1;
}
}
}else
{
*(ptr+i) = -1;
}
free(arr);
free(frr);
}
for(int j = 0;j<n;j++)
{
printf("%d\n",*(ptr+j));
}
}
The problem is that you set *(ptr+i) to -1 for each element of the array. This means that a later element of the array that is not repeated three times will reset *(ptr+i) to -1.
Change this
if(*(frr+g) >= 3)
{
*(ptr+i) = *(arr + g);
}
else
{
*(ptr+i) = -1;
}
to this
if(*(ptr+i) == -1 && *(frr+g) >= 3)
{
*(ptr+i) = *(arr + g);
}
and at the beginning add this
ptr = (int*)malloc(n * sizeof(int));
for (int i = 0;i < n; i++)
{
*(ptr + i) = -1;
But as has already been said in the comments you do not need either the ptr array or the frr array. You only run one test at a time so there is no need to keep all the test results before you print any of them out. And you only need to save the frequency of the current element you are testing, so you don't need an array for that either.
And make your code readable, change *(arr + g) to arr[g]. They both work exactly the same.
For starters this array allocation
ptr = (int*)malloc(n * sizeof(int));
does not make a sense. For each given sequence of numbers you can at once output whether the sequence contains three equal elements or not without storing this information in the allocated array.
Also allocating this auxiliary array
frr = (int*)malloc(size * sizeof(int));
makes the code unsafe and inefficient.
It does not make a sense to travers the array if an element that occurs already three times is found.
Otherwise this code snippet
if(*(frr+g) >= 3)
{
*(ptr+i) = *(arr + g);
}else
{
*(ptr+i) = -1;
}
for elements that are present in the tail of the array arr can incorrectly
set the value ptr[i] to -1 though early there was already found a preceding element that occurs three times.
Without the redundant arrays pointed to by the pointers ptr and frr the program can look the following way
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
size_t t = 0;
scanf( "%zu", &t );
while (t--)
{
size_t n = 0;
scanf( "%zu", &n );
int result = -1;
if (n)
{
int *a = malloc( n * sizeof( int ) );
for (size_t i = 0; i < n; i++)
{
scanf( "%d", a + i );
}
for (size_t i = 2; result == -1 && i < n; i++)
{
int count = 1;
for (size_t j = i; count != 3 && j-- != 0; )
{
if (a[j] == a[i]) ++count;
}
if (count == 3) result = a[i];
}
free( a );
}
printf( "%d\n", result );
}
}
I would approach the problem altogether differently. Since the range of the elements is not explicitly bounded, it is a bit tricksome to manage a frequency table. But the maximum number of elements in each test array is pretty small, so it is feasible to
declare an array large enough to hold all the elements of any test case
for each test case,
read all the elements into the (one) array
sort the array (qsort(), or roll your own insertion or selection sort)
scan the sorted array to easily detect and report values that appear at least thrice

segmentation failure while allocating memory for a 2D array in c

I have a function that returns all the combinations of letters possible in the alphabet with repetition in a word of length LENTH_MAX. The function returns these combinations in a 2D array call 'arr'.
Since calculating the total number of arrays is a pain because you need to calculate factorial numbers [ (n + r - 1)!/r!(n - 1)! ] I decided to increasingly reallocate memory for the arrays in 'arr' as needed.
I set a variable called capacity that determinetes the initial size of 'arr' and a constant called CAP_INCR that specifies the number of arrays for which memory will be reallocated in addition to the memory already assigned. The program compiles ok by if I set CAP_INCR to 1, so that each time a new combination is found new memory is allocated for that array, the program crushes with a Segmentation fault: 11 message, if I set CAP_INCR to 100 if finishes correctly but the output is wrong, the first combination 'a a a' is repeated twice and the last combination 'z z z' is mission.
I'd really appreciate some help. I'm a decent programer in other languages but I'm just starting with C.
The code is:
#include <stdio.h>
#include <stdlib.h>
const unsigned short LENGTH_MAX = 3;
const char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
#define CAP_INCR 1 /* memory increases */
unsigned char* combinations(unsigned char n, unsigned char r)
{
// n length of alphabet
// r length of figures
unsigned int set_counter = 0; //counting generated sequences
unsigned char *vector = NULL; //where the current figure is stored
unsigned char *arrTemp = NULL; // Temporary pointer store
unsigned int capacity = 100; // count current size of arr
unsigned char *arr = (unsigned char *)malloc(capacity * r * sizeof(unsigned char)); // multidimentional array
vector = (unsigned char *)malloc(sizeof(unsigned char) * r);
if(vector == NULL || arr == NULL)
{
fprintf(stderr, "error: insufficient memory\n");
exit(EXIT_FAILURE);
}
//initialize: vector[0, ..., r - 1] are 0, ..., r - 1
for(int l = 0; l < r; l++) //for(int l = 0; l < r; l++) // no repetition
vector[l] = 0;
//generate all successors
while(1)
{
set_counter++;
// check is arr current capacity is enough
if(set_counter > capacity)
{ // We need more memory
capacity += CAP_INCR;
arrTemp = (unsigned char *)realloc(arr, capacity * r * sizeof(unsigned char));
if(!arrTemp)
{
printf("Unfortunately memory reallocation failed.\n");
free(arr);
arr = NULL;
exit(0);
}
arr = arrTemp;
}
for(int x = 0; x < r; x++) { // assign a new combination to arr
//printf("%c ", alphabet[vector[x]]);
*(arr + set_counter*r + x) = vector[x];
}
//printf("(%u)\n", set_counter);
int j; //index
//easy case, increase rightmost element
if(vector[r - 1] < n - 1)
{
vector[r - 1]++;
continue;
}
//find rightmost element to increase
for(j = r - 2; j >= 0; j--) {
if(vector[j] != n - 1) {
break;
}
}
//terminate if vector[0] == n - r
if(j < 0)
break;
//increase
vector[j]++;
//set right-hand elements
for(j += 1; j < r; j++)
vector[j] = vector[j - 1];
}
return arr;
}
int main() {
unsigned char* arr = combinations(sizeof(alphabet)-1, LENGTH_MAX);
int c=0;
for (int i = 0; i < 3276; i++) // 3276 is the total number of combinations
{
for (int j = 0; j < 3; j++)
{
printf("%c ", alphabet[*(arr + i*3 + j)]);
}
printf("count: %d\n",++c);
}
return 0;
}

Addition Of Pointers in C [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Please go through the following loops:
I am especially confused about the first loop,
1st loop:
for(i = 0; i < n; i++)
{
scanf("%d", ptr + i);
}
for(i = 0; i < n; i++)
{
sum = sum + (*(ptr + i));
}
2nd loop:
int *x ;
for(i = 0; i < n; i++)
{
x = ptr + sizeof(i);
scanf("%d",x );
}
for(i = 0; i < n; i++)
{
x = ptr + sizeof(i) ;
sum = sum + (*x);
}
Why do entering the elements in the array by using malloc
using the above loops give the same result ?
Why are the first and second loop giving equal or right result ?
why are (ptr + i) and ptr + sizeof(i) working in same waY?
Entire program is
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define NULL 0
int main()
{
int *ptr;
int i, n, sum = 0 ;
float avg ;
printf("Enter the number of elements you want to store in the array.");
scanf("%d", &n);
ptr = (int *) malloc( n * sizeof(int)) ; /*Dynamic Memory allocation*/
if(ptr == NULL)
{
printf("The required amount of memory is not available. ");
getch();
exit(0);
}
else
{
printf("Enter the elements\n");
for(i = 0; i < n; i++)
{
scanf("%d", ptr + i);
}
for(i = 0; i < n; i++)
{
sum = sum + (*(ptr + i));
}
printf("\nThe sum of %d elements entered is = %d",n , sum );
avg = sum / n ;
printf("\nThe average of %d number of the array is %f", n, avg);
}
printf("\n");
getch();
}
why are (ptr + i) and ptr + sizeof(i) working in same waY?
They are not. In the first example, you read n values into an array (storing them in succesive elements), and then add those n values. In the second example, you read n values and store them all in the same element of the array (overwriting the previous element), so you end up with an array that is mostly uninitialized, but has one element set to the last value read. You then add that element to itself n times.
So you might end up with the same sum in both cases (for example, if your numbers are 1,3,2), or you might not.

Resources