Why a wrong number of 1 is printed? - arrays

My function should randomly insert a user-chosen number of 1 into my matrix. The difficulty lies in the fact that if a cell contains a 1 the cells around it must be set to 0. Why my code print a wrong number of 1? In the code below I had thought to first set the entire matrix to 0, then randomly generate a cell to be set to 1, after having checked it contains 0 and the distance between this cell and other cells containing 1 is >= 1. All this is done until the number m entered by the user becomes 0.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void initialize(int n, int a[n][n]);
void createMap(int n, int a[n][n], int m);
int check (int i, int j, int v, int w);
void print(int n, int a[n][n]);
int main(){
int n;
printf("Insert square matrix size: ");
scanf("%d", &n);
int m;
printf("Insert 1s number: ");
scanf("%d", &m);
int a[n][n];
initialize(n,a);
createMap(n,a,m);
}
//Filling the matrix with 0
void initialize(int n, int a[n][n]){
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
a[i][j] = 0;
}
}
}
//Setting in random position 1 value
void createMap(int n, int a[n][n], int m){
int x1; int x2;
int b[0][0];
while (m > 0){
int i = rand() % n;
int j = rand() % n;
if (a[i][j] == 0 && (check(i,j,x1,x2) == 1)){
a[i][j] = 1;
m--;
//I have to fill b array with coordinates and then to pass
//b array to check function to do the check in the whole b array
}
}
print(n,a);
}
//checking if I can set the value to 1
int check (int x1, int y1, int x2, int y2){
if (sqrt(pow((x1-x2),2) + pow((y1-y2),2)) >= 1){
return 1;
} else {
return 0;
}
}
//Printing the matrix
void print(int n, int a[n][n]){
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
printf("\t%d",a[i][j]);
}
puts("");
}
}

After generating the coordinates i and j, you should calculate the distance between that cell and the other cells set to 1. You can use the Manhattan formula to do that.
If the distance between the newly generated cell and the other cells set to 1 is grater than or equal to 1, you can go ahead and generate the other ones, otherwise you should set it back to zero and generate new coordinates.

This is homework right?
A few issues:
You have a variable matrix that you don't use.
You set a[k][l] = 1; before you know what the old value was, and therefore can't tell if m should be incremented or not.
Your bounds checking is messy, it is difficult to see if it is correct, and if you update m and all array elements around a[k][l] correctly. Nobody wants to look at messy code, unless they get paid. They will just assume that it is wrong. So that part of the code is by definition wrong, and nobody can tell you why.
Your bounds checking assumes you have a 4x4 array.
... and a few others.
Point 1 is easy to fix, and it is not important. It just adds to the ugliness of your code.
Point 2 is solved by only updating a[k][l] and m if a[k][l] was zero:
if (a[k][l] == 0)
{
a[k][l] = 1;
m--;
}
Point 3 can be most easily fixed by creating a separate function that does resetting of single array elements with bounds checking. Since I assume this is homework, I am not going to write this for you, unless you have made an honest try yourself first. The function signature could look like this:
/*
Set value of `a[line][column]` to zero and increment `*m` if value
was changed.
Nothing is done if `line` or `column` are out of bounds.
*/
void matrix_element_reset(int n, a[n][n], int line, int column, int *m);
You can then easily reset array elements around a[k][l] like this:
/* This can be simplified with loops */
matrix_element_reset(n, a, k-1, l, &m);
matrix_element_reset(n, a, k, l, &m);
matrix_element_reset(n, a, k+1, l, &m);
.....
Point 4: Your variable n stores the dimension of your matrix. Use it.

Related

Segmentation Fault During Matrix Multiplication

I am new to C coding, and am trying to implement standard matrix multiplication. My code works fine for square matrices, but refuses to accept a column vector. Here is my attempt at the code. Any help would be much appreciated.
//---------------------------------------IMPORTING NECESSARY C PACKAGES AND DEFINING EXECUTION CONSTANTS-------------------------------------------//
#include <stdio.h> // Standard input output library
#include <math.h> // Mathematical function library
#include <stdlib.h> // General purpose standard library
#define true 1
#define false 0
typedef long double numeric; // Using the long double datatype to avoid overflows during computations
//-------------------------------------------------------------------------------------------------------------------------------------------------//
//----------------------------------------------------------------FUNCTION DECLERATION-------------------------------------------------------------//
numeric **create_matrix(int x, int y); // To dynamically allocate memory and create a matrix
void input_matrix(numeric **matrix, int m, int n); // To accept a matrix
void print_matrix(numeric **l, int x, int y); // To print a matrix
numeric **standard_matrix_multiplication(int m, int n, int l); // To multiply two matrices
//-------------------------------------------------------------------------------------------------------------------------------------------------//
//------------------------------------------------------------------DRIVER CODE--------------------------------------------------------------------//
int main(int argc, char *argv[]) {
int m, n, l; int choice;
printf("Enter the matrix operation to be performed using the corresponding index number.\n");
printf("\n");
printf("1.\tMatrix Multiplication");
printf("\n");
scanf("%d", &choice);
switch(choice) {
case 1 :
printf("Enter the number of rows in the first matrix\n");
scanf("%d", &m);
printf("Enter the number of columns in the first matrix\n");
scanf("%d", &n);
printf("Enter the number of columns in the second matrix\n");
scanf("%d", &l);
printf("Enter both matrices.\n");
numeric **matrix_x;
matrix_x = create_matrix(m, l);
matrix_x = standard_matrix_multiplication(m, n, l);
print_matrix(matrix_x, m, l);
break;
}
}
//-------------------------------------------------------------------------------------------------------------------------------------------------//
//----------------------------------------------------------MATRIX MULTIPLICATION IMPLEMENTATIONS--------------------------------------------------//
numeric **standard_matrix_multiplication(int m, int n, int l) {
numeric **matrix_a; numeric **matrix_b; numeric **matrix_k;
matrix_a = create_matrix(m, n);
matrix_b = create_matrix(n, l);
matrix_k = create_matrix(m, l);
input_matrix(matrix_a, m, n);
print_matrix(matrix_a, m, n);
input_matrix(matrix_b, n, l);
for(int i = 0; i < m; i++) {
for (int j = 0; j < n; j ++) {
for (int k = 0; k < l; k++) {
matrix_k[i][j] += matrix_a[i][k] * matrix_b[k][j];
}
}
}
return matrix_k;
}
//-------------------------------------------------------------------------------------------------------------------------------------------------//
//---------------------------------------------------------------HELPER FUNCTIONS------------------------------------------------------------------//
numeric **create_matrix(int x, int y) {
numeric **matrix = (numeric**)malloc(x * sizeof(numeric*)); // Dynamically creating an array of pointers
for (int i = 0; i < y; i++) {
matrix[i] = (numeric*)malloc(y * sizeof(numeric)); // Dynamically allocating memory for each columns of the matrix
}
return matrix;
}
void input_matrix(numeric **matrix, int m, int n) {
printf("Enter the elements of the matrix, row wise.\n"); // Instructing the user on matrix entry
printf("For example, to enter the matrix\n");
printf("\t\t1\t2\n");
printf("\t\t3\t4\n");
printf("enter 1, 2, 3, and 4 in that order.\n");
for (int i = 0; i < m; i++) { // Iterating through the rows and columns of the matrix
for (int j = 0; j < n; j++) {
scanf("%Lf", &matrix[i][j]); // Accepting each element
}
}
}
void print_matrix(numeric **l, int x, int y) { // To print a matrix
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
printf("%0.10Lf\t", l[i][j]); // Printing numeric type values
}
printf("\n");
}
printf("\n");
}
As of now, I have only written one switch case, and that is for matrix multiplication. So I chose 1. I gave 2, 1, 2 as my inputs for the number of rows in the first matrix, number of columns in the first matrix, and number of columns in the second matrix respectively. I have given a print statement in line 52, and it isn't executing it for the above input, giving a segmentation fault instead. Could someone please help me out?
Yes there are some issues with your code that gives segfault error during runtime.
The Matrix multiplication logic part of the code needs to be corrected as follows
for(int i = 0; i < m; i++) {
for (int j = 0; j < l; j ++) {
for (int k = 0; k < n; k++) {
matrix_k[i][j] += matrix_a[i][k] * matrix_b[k][j];
because k should iterate till the no of columns in 1st matrix which is n but not till l.
And there is a slight correction needed in create_matrix function.
You use y (i.e. no of columns in the matrix) in your for instead of x (no of rows in matrix).
If x < y, you end up outside of the memory you allocated.
If x > y, you end up with uninitialized pointers.
So change it as follows
for (int i = 0; i < x; i++) {
matrix[i] = (numeric*)malloc(y * sizeof(numeric));
After these corrections try executing the code, you should get the expected results without any segfault errors
Here is the complete working code
#include <stdio.h> // Standard input output library
#include <math.h> // Mathematical function library
#include <stdlib.h> // General purpose standard library
#define true 1
#define false 0
typedef long double numeric; // Using the long double datatype to avoid overflows during computations
//-------------------------------------------------------------------------------------------------------------------------------------------------//
//----------------------------------------------------------------FUNCTION DECLERATION-------------------------------------------------------------//
numeric **create_matrix(int x, int y); // To dynamically allocate memory and create a matrix
void input_matrix(numeric **matrix, int m, int n); // To accept a matrix
void print_matrix(numeric **l, int x, int y); // To print a matrix
numeric **standard_matrix_multiplication(int m, int n, int l); // To multiply two matrices
//-------------------------------------------------------------------------------------------------------------------------------------------------//
//------------------------------------------------------------------DRIVER CODE--------------------------------------------------------------------//
int main(int argc, char *argv[]) {
int m, n, l; int choice;
printf("Enter the matrix operation to be performed using the corresponding index number.\n");
printf("\n");
printf("1.\tMatrix Multiplication");
printf("\n");
scanf("%d", &choice);
switch(choice) {
case 1 :
printf("Enter the number of rows in the first matrix\n");
scanf("%d", &m);
printf("Enter the number of columns in the first matrix\n");
scanf("%d", &n);
printf("Enter the number of columns in the second matrix\n");
scanf("%d", &l);
printf("Enter both matrices.\n");
numeric **matrix_x;
matrix_x = create_matrix(m, l);
matrix_x = standard_matrix_multiplication(m, n, l);
print_matrix(matrix_x, m, l);
break;
}
}
//-------------------------------------------------------------------------------------------------------------------------------------------------//
//----------------------------------------------------------MATRIX MULTIPLICATION IMPLEMENTATIONS--------------------------------------------------//
numeric **standard_matrix_multiplication(int m, int n, int l) {
numeric **matrix_a; numeric **matrix_b; numeric **matrix_k;
matrix_a = create_matrix(m, n);
matrix_b = create_matrix(n, l);
matrix_k = create_matrix(m, l);
input_matrix(matrix_a, m, n);
print_matrix(matrix_a, m, n);
input_matrix(matrix_b, n, l);
//print_matrix(matrix_b, n, l);
for(int i = 0; i < m; i++) {
for (int j = 0; j < l; j ++) {
for (int k = 0; k < n; k++) {
matrix_k[i][j] += matrix_a[i][k] * matrix_b[k][j];
}
}
}
return matrix_k;
}
//-------------------------------------------------------------------------------------------------------------------------------------------------//
//---------------------------------------------------------------HELPER FUNCTIONS------------------------------------------------------------------//
numeric **create_matrix(int x, int y) {
numeric **matrix = (numeric**)malloc(x * sizeof(numeric*)); // Dynamically creating an array of pointers
for (int i = 0; i < x; i++) {
matrix[i] = (numeric*)malloc(y * sizeof(numeric)); // Dynamically allocating memory for each columns of the matrix
}
return matrix;
}
void input_matrix(numeric **matrix, int m, int n) {
printf("Enter the elements of the matrix, row wise.\n"); // Instructing the user on matrix entry
printf("For example, to enter the matrix\n");
printf("\t\t1\t2\n");
printf("\t\t3\t4\n");
printf("enter 1, 2, 3, and 4 in that order.\n");
for (int i = 0; i < m; i++) { // Iterating through the rows and columns of the matrix
for (int j = 0; j < n; j++) {
scanf("%Lf", &matrix[i][j]); // Accepting each element
}
}
}
void print_matrix(numeric **l, int x, int y) { // To print a matrix
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
printf("%0.10Lf\t", l[i][j]); // Printing numeric type values
}
printf("\n");
}
printf("\n");
}
You are not allocating enough memory for matrix_k. You are allocating memory for m rows and l columns, but you are trying to access m rows and n columns. You need to allocate memory for m rows and n columns. You can do this by changing the line
matrix_k = create_matrix(m, l);
to
matrix_k = create_matrix(m, n);
This is the same problem you had in your other question.

How to use helper functions to fill an array of user input size?

This is supposed to be a simple program, first asking the user the size of the square array (from 1 to 10) then asking the user to input the numbers into the array and finally printing out the array with the inputted numbers.
However, now inputting something such as the size of 2, with values 1, 2, 3, 4
Instead of getting the array
1.00 2.00
3.00 4.00
printed out, it prints out a long wall of 0.00's with the correct values somewhere in there.
From my understanding it's required to give bounds when declaring a helper function with a multidimensional array like so void someFunct(int arr[][MAX]);, which in this case I declared the max size to be 10. But if I'm not mistaken the problem might be coming from me doing something wrong there?
The code I was testing:
#include <stdio.h>
int numInput(char[]);
void fillArray(double[][10],int);
void printArray(double[][10],int);
int main() {
// GET SQUARE ARRAY SIZE
int n = numInput("Insert the dimension of the square array(1-10): ");
// FILL THE SQUARE ARRAY A[n][n]
double A[n][n];
fillArray(A, n);
// PRINT OUT ARRAY A[n][n]
printArray(A, n);
return 0;
}
int numInput(char text[]){
int num;
do{
printf("%s", text);
scanf("%d", &num);
}while(num < 1 || num > 10);
printf("\n");
return num;
}
void fillArray(double arr[][10],int size){
int i, j;
for(i = 0; i < size; i++){
for(j = 0; j < size; j++){
printf("Insert A[%d][%d]: ", i, j);
scanf("%lf", &arr[i][j]);
}
}
}
void printArray(double arr[][10],int size){
int i, j;
for(i = 0; i < size; i++){
for(j = 0; j < size; j++){
printf(" %.2lf ", arr[i][j]);
}
printf("\n");
}
printf("\n");
}
Simply change your functions to use the specified variable size:
void fillArray (int size, double arr[size][size]);
void printArray (int size, double arr[size][size]);
Note that the size parameter needs to be declared to the left of the array parameter.
Change double A[n][n] to double A[10][10];.
If n is e.g. 3, then double A[n][n] ends up being a double A[3][3] which is not compatible with a double arr[][10].
Variable length arrays are not that useful after all, use them with care.

C- whats the problem with this code? I try to multiply one matrix in another matrix in func and get new matrix but i get segmentation fault

This is the program I'm working on. The task is to multiply 2 matrices. The number of columns in Matrix A are the same as the number of rows in Matrix B. I give the user the option to insert what the two matrices contain .
this my code:
#include <stdio.h>
void multiplyMat(int n,int p,int c,int m,int d,int q,int k,int **multiply,
int **first,int **second);
int main()
{
int m, n, p, q, c, d, k;
int first[10][10], second[10][10], multiply[10][10];
printf("Enter number of rows and columns of first matrix\n");
scanf("%d%d", &m, &n);
printf("Enter elements of first matrix\n");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);
printf("Enter number of rows and columns of second matrix\n");
scanf("%d%d", &p, &q);
printf("Enter elements of second matrix\n");
for (c = 0; c < p; c++)
for (d = 0; d < q; d++)
scanf("%d", &second[c][d]);
multiplyMat(n,p,c,m,d,q,k,multiply,first,second);
printf("Product of the matrices:\n");
for (c = 0; c < m; c++) {
for (d = 0; d < q; d++)
printf("%d\t", multiply[c][d]);
printf("\n");
}
return 0;
}
void multiplyMat(int n,int p,int c,int m,int d,int q,int k,int **multiply,
int **first,int **second){
int sum=0;
if (n == p){
for (c = 0; c < m; c++) {
for (d = 0; d < q; d++) {
for (k = 0; k < p; k++) {
sum = sum + first[c][k]*second[k][d];
}
multiply[c][d] = sum;
sum = 0;
}
}
}
else
printf("The matrices can't be multiplied with each other.\n");
}
I get the "segmentation fault".
it happend when the code get in "sum = sum + first[c][k]*second[k][d]"
what i do that cause it?
maybe its happend because i use wrong defnion of pointers.
int **multiply is "a pointer to a pointer to an int", also interpreted as "a pointer to an array of pointers to ints".
So int **multiply and int *multiply[] are the same and you can use i= multiply[1][3]; The compiler will dereference multiply, add the size of 1 pointer, then dereference that element and add the size of 3 ints, then gets that int and assign it to i.
But you pass a 2 dimensional array. A 2 dimensional array is not an array of columns containing pointers to the rows. It just is a block of memory in which you have columns times a row laid out neatly one after the other.
Now you make a function to do the multiplication. But that function does not know how many columns a row has. So the compiler cannot evaluate multiply[1][2] as the third element of the second row of multiply[10][10].
To achieve what you want there are three possibilities:
declare the matrix with a size in your function of the row size, e.g. multiply[][10]. This allows the compiler to do the address calculations inside your functions (you must still tell it how many rows there are)
with modern compilers, you can dynamically specifiy the array sizes:
f(int rows, int cols, int a[rows][cols])
do the address calculations yourself. (I will not go into this option; I hope you have a modern compiler).

Function to sum all permutations

some time ago I wrote a program that prints all possible permutations of of a given array, even printing all partial arrays:
#define MAXARRAY 32
#include <stdio.h>
void combinations(int array[], int temp[], int start, int end, int index, int r);
void print_combinations(int array[], int n, int r){
int temp[r];
combinations(array, temp, 0, n-1, 0, r);
}
void combinations(int array[], int temp[], int start, int end, int index, int r){
if (index == r){
for (int j=0; j<r; j++)
printf("%d ", temp[j]);
printf("\n");
return;
}
for (int i=start; i<=end && end-i+1 >= r-index; i++){
temp[index] = array[i];
combinations(array, temp, i+1, end, index+1, r);
}
}
int main(){
int array[MAXARRAY];
int r;
int n = sizeof(array)/sizeof(array[0]);
int i=MAXarray, j;
for(j=0;j<MAXARRAY;j++){
array[j]=j+1;
}
for(r=0;r<=i;r++)
print_combinations(array, n, r);
}
Now I'm trying to convert this program to do the following:
Instead of printing the permutations, I want to sum up ALL permutations and compare the sum with a fixed value, and if the sum of numbers in the permutation truly is equal to that fixed value, it increases the counter so in the end I could check how many sums of permutation equals that value. This is what I came up with for now:
#define MAXARRAY 32
#include <stdio.h>
int combinations (int array[], int temp[], int start, int end, int index, int r);
void print_combinations (int array[], int n, int r){
int temp[r];
combinations(array, temp, 0, n-1, 0, r);
}
int combinations (int array[], int temp[], int start, int end, int index, int r){
int sum=0, counter=0;
if (index == r) {
for (int j=0; j<r; j++){
sum=sum+temp[j];
}
if(sum==264){
counter++;
}
}
for (int i=start; i<=end && end-i+1 >= r-index; i++){
temp[index] = array[i];
combinations(array, temp, i+1, end, index+1, r);
}
return counter;
}
int main()
{
int array[MAXARRAY];
int r;
int n = sizeof(array)/sizeof(array[0]);
int i=MAXARRAY, j;
for(j=0;j<MAXARRAY;j++){
array[j]=j+1;
}
for(r=0;r<=i;r++)
print_combinations(array, n, r);
I don't know how to alter this correctly to get what I want, precisely I am a bit lost with how to switch up the void function to print a counter that does not appear in the function, and I am unsure if I can just easily "alter" this code to get what I want, or I just need to write completely new functions.
You want to know in how many ways you can pick numbers from a given set so that they sum up to a given target value. You seem to approach this the wrong way, because you have mixed up permutations and combinations.
Permutations are different arrangements of a set of items with a fixed size n and number of possible arrangements is n! if all of the items are different. That's of no use here, because summation is commutative; the order of operands doesn't matter.
Combinations tell you which items of a set are included and which are not. This is what you want here. Luckily for you, there are only 2ⁿ possilbe ways to pick items from a set of n, including all items or none.
You can also solve this recursively. Each level of recursion treats one item and you can either chose to include it or not. For thee items, you get the following decision tree:
0
/ \
0 1
/ \ / \
0 2 0 2
/ \ / \ / \ / \
0 3 0 3 0 3 0 3
sum 0 3 2 5 1 4 3 6
Take the left branch to omit an item and take the right branch to include it. This will give you the sum of 3 twice and all other sums from 0 to 6 inclusively once. There are 8 possible paths.
The program below does that:
#include <stdlib.h>
#include <stdio.h>
#define N 32
#define TARGET 264
/*
* Print the summands
*/
void print(const int a[], int n)
{
int i;
for (i = 0; i < n; i++) {
if (i) printf(" + ");
printf("%d", a[i]);
}
puts("");
}
/*
* Actual recursive combination function
*/
size_t combine_r(const int pool[], // summand pool
int res[], // currently included items
int max, // length of pool
int n, // length of res
int i, // current item's index in pool
int sum, // running sum
int target) // desired target
{
int count = 0;
if (i == max) {
if (sum == target) {
//print(res, n);
count++;
}
} else {
count += combine_r(pool, res, max, n, i + 1, sum, target);
res[n++] = pool[i];
count += combine_r(pool, res, max, n, i + 1,
sum + pool[i], target);
}
return count;
}
/*
* Interface function for the recursive function.
*/
size_t combine(const int pool[], int n, int target)
{
int res[n];
return combine_r(pool, res, n, 0, 0, 0, target);
}
int main()
{
int pool[N];
size_t n;
int i;
for (i = 0; i < N; i++) pool[i] = i + 1;
n = combine(pool, N, TARGET);
printf("%zu combinations.\n", n);
return 0;
}
The function goes down each path and records a hit if the sum equals the target. The number of hits in each subtree is returned as you return from the recursion and go up the tree, so that the root level you've got the total number of hits.
The function combine is just a front-end to the actual recursive function, so that you don't have to pass so many zeros from main. The arguments for the recursive function could probably be reduced and organised more elegantly. (Tow of them exist only because in C you have to pass i the length of an array. If you just want to count the possibilities, you can get rid of res and n, which just serve to print the array.)

Sum of array in C

I'm working on a small program for school and can't get my array of doubles to sum properly. The specific error I'm getting is
warning C4244: 'return': conversion from 'double' to 'int', possible loss of data
on the line where sum is returned. And the sum displayed is gibberish.
The code is intended to:
fill an array of doubles with user input,
print the doubles on the screen in a column,
add up all the doubles in the array, and
print the sum onto the screen.
Code
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#define MAX_SIZE 15
void FillArray(double a[], int *i);
void PrintArray(double a[], int i);
SumArray(double a[], int *i);
int main()
{
double input[15];
int input_size;
double sum;
FillArray(input, &input_size);
PrintArray(input, input_size);
sum = SumArray(input, &input_size);
printf("The sum is %f\n", sum);
return 0;
}
void FillArray(double a[], int *i)
{
int k;
printf("Filling an array of doubles\n");
printf("How many doubles do you want to enter (<15)\n");
scanf(" %d", i);
for (k = 0; k <*i; k++)
{
printf("Enter double:\n");
scanf("%lf", &a[k]);
}
}
void PrintArray(double a[], int i)
{
int k;
printf("Printing an array of integers:\n");
for (k = 0; k<i; k++)
{
printf("%f\n", a[k]);
}
printf("\n");
}
SumArray(double a[], int *i)
{
int k;
double sum = 0;
for (k = 0; k<*i; k++);
{
sum +=a[k];
}
return (sum) ;
}
You need to specify double SumArray(...) instead of merely SumArray(...) where you declare and define the function. If you do not specify a return type, int is assumed. Specifically:
void FillArray(double a[], int *i);
void PrintArray(double a[], int i);
double SumArray(double a[], int *i);
/*^^^^^^-- add return type*/
int main()
and
double SumArray(double a[], const int numElements)
/*^^^^^^- same deal*/ /* also ^^^^^ ^^^^^^^^^^^ */
{
int k;
double sum = 0.0; /* Edit 3: 0.0 rather than 0 for clarity */
for (k = 0; k < numElements; ++k) /* no ; here! --- Edit 3: ++k for speed and good practice */
{ /* ^^^^^^^^^^^ */
sum +=a[k];
}
return (sum) ;
}
Edit Also, you can use const int numElements instead of int *i in SumArray. You don't need to modify the value inside SumArray, so you don't need the * and you can specify const. And it's a good practice to give your variables descriptive names, e.g., numElements instead of i. That will help you understand your own code when you have to maintain it later! (Ask me how I know. ;) )
To use this, you also need to change the call in main to remove the &:
sum = SumArray(input, input_size);
/* ^ no & here */
Edit 2 As #BLUEPIXY pointed out, the trailing ; on the for loop was misplaced. As a result, the {} block ran once, after the loop had completed. That would be a significant cause of the "gibberish" you saw: the effect was to set k=numElements and then set sum=a[numElements], which was a non-existent element. So the sum was being set to whatever random memory contents happened to be after a.

Resources