Given an array of integers, find the sum of its elements - c

Given an array of integers, find the sum of its elements.
my problem is that; in c language you have only fixed size array;
my code does not print the sum of random size array which the question demands;[1,2,3,4,5,-------n elements] it prints for only for ex 6 or defnite size aray; using a loop;
#include <stdio.h>
int main() {
int i;
scanf("%d\n",&i);
int a[6];
int sum=0;
for(i=0;i<=5;i++)
scanf("%d\n",&a[i]);
for(i=0;i<=5;i++)
sum=sum+a[i];
printf("%d\n",sum);
return 0;
}

It seems you want to let you user input the number of elements in the array. Your code scan that information into variable i. Therefore you can't use variable i as counter in the for loops. You need two different variables. One variable to hold the the number of integers to include in the sum and another variable for the loops.
Further to get a variable sized array, you need to use the users input when you define the array. This is called VLA (Variable Length Array).
Something like:
#include <stdio.h>
int main() {
int i;
int N = 0; // New variable holding the number of integers in the sum
scanf("%d\n",&N); // scan into N
int a[N]; // Use N for the VLA
int sum=0;
for(i=0;i<N;i++) // Use N as limit
scanf("%d\n",&a[i]);
for(i=0;i<N;i++) // Use N as limit
sum=sum+a[i];
printf("%d\n",sum);
return 0;
}
That said - be careful about VLAs. If the user inputs a high number for N a stack overflow may occur. If you want to use VLAs your code should enforce a maximum
limit for the users input.
It's typically better to use dynamic allocation instead of VLA. Like:
#include <stdio.h>
#include <stdlib.h>
int main() {
int i;
int N = 0;
scanf("%d\n",&N);
int *a = malloc(N * sizeof *a); // Dynamic allocation
if (a == NULL) exit(1); // Check for allocation failure
int sum=0;
for(i=0;i<N;i++)
scanf("%d\n",&a[i]);
for(i=0;i<N;i++)
sum=sum+a[i];
printf("%d\n",sum);
free(a); // Free allocated memory
return 0;
}
Some extra comments:
1) To calculate the sum you actually don't need an array. Just scan into some int and add it to sum. No need for storing it in an array first.
2) Always check the return value of scanf. Example: if (scanf("%d\n",&N) != 1) exit(1);

Related

C - How would I extract Even numbers from an array and place them into another array called EvenNumbers?

I'm tasked with writing a function that will identify all the even numbers in an sample array {10,2,9,3,1,98,8] and place them in an array called EvenNumbers. I have to allow the function so that it works with different combinations of numbers in the array not just the numbers in the sample array above.
I'm wondering is there any way to add numbers to an array that could be different every time? How would I extract the even numbers an place them into an array? Also
for the even array size its giving me an error that the expression must have a constant value but when I use const int it still gives me that error.
Here is the full question.
"Using the array of sample values {10,2,9,3,1,98,8}, write a function that will identify all the even numbers in an array and place it in an array called EvenNumbers. The function must work in all cases, not just in the case of the array shown. Assume that the array size is always available through a global constant called MAX"
Here is what I have so far. I've no idea how I will extract the even numbers from a for loop and place them in an array. I also dont know what the "expression must have a constant value" is about?
#include <stdio.h>
#include <stdlib.h>
void EvenNumber(int Array[], int size);
int main()
{
int array[7] = { 10,2,9,3,1,98,8 };
EvenNumber(array, 7);
}
void EvenNumber(int Array[], int size)
{
int i;
int EvenArraySize;
for (i = 0; i < size; i++)
{
if (Array[i] % 2 == 0)
{
EvenArraySize++;
}
}
int Even[EvenArraySize];
}
The right way to go is to use malloc to allocate just the right amount of memory.
Count the number of even numbers
Allocate the space needed to store them
Copy even numbers in this space
Do whatever you want with these numbers
Free the allocated space
Snippet:
#include <stdio.h>
#include <stdlib.h>
#define MAX 7
int
main()
{
int array[] = {10,2,9,3,1,98,8};
int *even_numbers;
int i, nb_even_numbers;
for (i = 0, nb_even_numbers = 0; i < MAX; i++)
{
if (array[i] % 2 == 0)
nb_even_numbers++;
}
even_numbers = malloc(sizeof(int) * nb_even_numbers);
if (!even_numbers)
{
perror("malloc");
return 1;
}
for (i = 0, nb_even_numbers = 0; i < MAX; i++)
{
if (array[i] % 2 == 0)
even_numbers[nb_even_numbers++] = array[i];
}
/* do your stuff here */
free(even_numbers);
return 0;
}
First, you can never return a statically declared array from a function (even though you don't explicitly try, your Even array is destroyed when EvenNumber returns) Why? The function stack frame for EvenNumber is released for reuse on return and any locally declared arrays are no longer valid.
You either need to pass a second array as a parameter to EvenNumber, or you can dynamically allocate storage for Even in EvenNumber (with, e.g. malloc or calloc or realloc) and return a pointer to the beginning of the array. (you must also have some way to return the size or use a constant for a max size).
There is no need to use % (modulo) to test whether a number is odd/even. All you need to do is look at bit-0 (little endian). If it is 0, then the number is odd, if it is 1, then its even. Much more efficient than calling modulo which incorporates division.
Finally, main is type int and therefore returns a value.
Putting those pieces together, you can do something simple like the following:
#include <stdio.h>
#include <stdlib.h>
void EvenNumber (int *array, int *even, int size, int *esize);
int main (void)
{
int array[] = { 10,2,9,3,1,98,8 },
i, n = sizeof array / sizeof *array,
even[n], /* a VLA of the same size as array is fine here */
esize = 0;
EvenNumber (array, even, n, &esize);
printf ("array: ");
for (i = 0; i < n; i++)
printf (" %2d", array[i]);
printf ("\neven : ");
for (i = 0; i < esize; i++)
printf (" %2d", even[i]);
putchar ('\n');
return 0;
}
void EvenNumber (int *array, int *even, int size, int *esize)
{
int i;
for (i = 0; i < size; i++)
if ((array[i] & 1) == 0) /* simply looking at bit-0 is all you need */
even[(*esize)++] = array[i];
}
Note: esize is passed as a pointer to EvenNumber and updated within the function so that the number of elements in even are available back in the calling function (main() here).
Example Use/Output
$ ./bin/arrayeven
array: 10 2 9 3 1 98 8
even : 10 2 98 8
Let me know if you have any further questions.

array undeclared ,first used in the function error during dynamic memory allocation

Here i am writing a program which will do two things
1.get a number between 0 to 102,separate them and store them in an array
2.print the array for each number
For that purpose i wrote an if-else block which will initialize an array each time exactly according to the size of the current integer value which is denoted by variable called num
Meaning that if i have a number of single digit it will create an array of one element,If number is two digit long it will create an array of two element.But whenever i run the code i get the error mentioned in question title.
What might be the reason for that and how to solve this issue?
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int mirror(int num,int *arr,int i);
int main(){
int num=0,range=1;
while(num<102){
if(num<(int)pow(10,range))
{
int *arr =(int *)malloc(range*sizeof(int));
}else{
range+=1;
int *arr =(int *)malloc(range*sizeof(int));
}
int i = 0;
mirror(num,arr,i);
for(i=0;i<range;i++){
printf("%d ",arr[i]);
}
printf("\n");
num++;
}
}
int mirror(int num,int *arr,int i){
if(num == 0){
return 0;
}
arr[i] = num%10;
mirror(num/10,arr,++i);
}
The scope of pointer arr is only within the if-else block. So, it's not available outside of it.
Declare it outside the if-else block and you'll be able to use it as you have.
int *arr;
if(num<(int)pow(10,range))
{
arr = malloc(range*sizeof(int));
}else{
range += 1;
arr = malloc(range*sizeof(int));
}
Notice I have removed the cast of the malloc() return value. It's needless in C and error-prone. See: http://c-faq.com/malloc/mallocnocast.html
Array is local variable in if/else statement. You should put declaration of array in outer block of while and assignment in conditional block.

Trouble with using calloc with an array and returning a pointer

As a reference this is the second part of my assignment:
int* generateFibonacci(int size);
This function will take as input an integer called size. The value contained in the size variable
will represent how many numbers in the Fibonacci sequence to put into the array. The function
will use calloc to create the array of this size and then fill the array with size numbers from the
Fibonacci sequence, starting with 1 and 1. When the array is complete the function will return a
pointer to it.
My trouble come in play when I get the error in line 8 "warning: assignment makes and integer from pointer without a cast".
Another error I get is in line 19 "warning: return makes pointer from integer without a cast".
So my question is, how am I suppose to set up calloc to make the array with a size from a user, then return a pointer to it?
#include <stdio.h>
#include <stdlib.h>
int* generateFibonacci(int size)
{
int i, array[size];
array[size]=(int*)calloc(size, sizeof(int));
array[0]=0;
array[1]=1;
for(i = 2; i < size+1; i++)
array[i] = array[i-2] + array[i-1];
return *array;
}
void printHistogram (int array[], int size)
{
int i, j;
for(i=0; i <= size; ++i)
{
for(j=0; j < array[i]; j++)
{
printf("*");
}
printf("\n");
}
}
int main(void)
{
int array[100], size;
printf("how big will your Fibionacci number be? ");
scanf("%i", &size);
generateFibonacci(size);
printHistogram(array, size);
return 0;
}
how am I suppose to set up calloc to make the array with a size from a user, then return a pointer to it?
For a 1D array of int * Use printf() and scanf()
int *array = {0}; //Note, leaving this initialization method for posterity
//(See related comments below.)
//however agreeing with commentator that the more idiomatic
//way to initialize would be: int *array = NULL;
size_t size = 0;
printf("Enter order of array");
scanf("%d", &size);
array = malloc(size);//create memory with space for "size" elements
if(array){//do other stuff}
But it is unclear from your example, and the comment if you really intend using a 2D array....
As stated in the comments, You have created an int array, then attempted to create memory for it.
int i, array[size];
...
array[size]=(int*)calloc(size, sizeof(int));//wrong
As it is created, array does not need memory. Memory is created on the stack as automatic.
If you wanted a 2D array of int. Then you could do it like this:
int *array[size]; //create a pointer to int []
With this, you can create an array of arrays (in concept) in this way:
for(i=0;i<size;i++) array[i]= calloc(size, sizeof(int));//do not cast the output, not necessary
Now, you essentially have a size x size 2D array of int. It can be assigned values in this manner:
for(i=0;i<size;i++)
for(j=0;j<size;j++)
array[i][j]=i*j;//or some more useful assignment
By the way, adjust the parameters of the calloc() statement as needed, but note, casting its output is not necessary.
Regarding the return statement, your function is prototyped to return a int *.
int* generateFibonacci(int size){...} //requires a return of int *
If you decide to use a 1D array, i.e. int *array={0} (requiring that you allocate memory), then return:
return array;//array is already a `int *`, just return it.
If you are using the 2D array, then to return a int *, you must decide which of the size elements of the array you want to return:
return array[i];//where `i` can be any index value, from 0 to size-1

A simple "for" command doesnt work using only the stdio library

Using the same machine and IDE as reffered in my other question (third paragraph at Problems in code or my IDE/comp is bugged?)
I try to run this code:
#include <stdio.h>
#define n 3
int main()
{
int i;
float values[n],sumval,svmean,tmp;
for(i=0;i<n;++i)
{
scanf("%f",&tmp);
values[i]=tmp;
sumval = sumval + values[i];
}
svmean = sumval/n;
printf("%f \n",svmean);
return(0);
}
The above code is supposed to run this formula
That means that it has to add some values and divide the result by their total number.
As you see above I made an array with random n positions and I ask the user to fill in a value for each position then add them all up and divide them.
The problem is that it doesnt work. It outputs only the result 7 no matter what the iput is.
BUT if I include stdlib.h to the code it works fine.
so
Question A: why the code does not work properly using only the
stdio.h library? which element of the code does require the stdlib.h
library?
As you see the array values[n] seems to have an random n number of cells but actually I have already set this numer to be equal to 3 (using #define)
Question B: Is there a way to run a code with the same porpuse but letting the user to define the size of the array values[n] or in other words let the user input an integer that sets the value of n in values[n]?
First of all, you forgot to initialize sumval. You want it to be 0 at the beginning.
If you want the size of the array to be decided at runtime, you have to allocate it dynamically using malloc, for example like this:
int n;
float *values,sumval=0,svmean,tmp;
scanf("%d", &n);
values = (float *) malloc (n * sizeof(float));
Later, you should release the memory allocated by calling free:
free(values);
Initialize sumVal to o. Because for first iteration it adds garbage+values[i] into sumValue.
#include <stdio.h>
#define n 3
int main()
{
int i;
float values[n],sumval=0,svmean,tmp;
for(i=0;i<n;++i){
scanf("%f",&tmp);
values[i]=tmp;
sumval = sumval + values[i];
}
sumean = sumval/n;
printf("%f \n",svmean);
return(0);
}
The problem is that you do not initialize sumval. You should set it to 0.0 before you for loop.
The change occurring when including/not-including stdio.h is probably due to some initialization functions using the stack, and changing the values in memory, before you enter your function, and it happen that this memory is used for your sumval variable.
But you should NOT rely on this.
Question A answer
In the code you posted there is no need for stdlib.h. This library is needed if you use a function for allocating memory dynamically, such as malloc().
Question B answer:
This is a way to do what you want:
#include <stdio.h>
int main()
{
int i, choice;
float *values,sumval,svmean,tmp;
printf("Please enter the size of the array: ");
scanf("%d", &choice);
values = (float*) malloc(choice*sizeof(float));
for(i=0;i<n;i++){
scanf("%f",&tmp);
values[i]=tmp;
sumval = sumval + values[i];
}
svmean = sumval/n;
printf("%f \n",svmean);
free(values);
return 0;
}
Also, I modified the incrementation of i in the for statement to increase after running the loop.
Try this..
#include <stdio.h>
int main()
{
int i = 0;
int n = 0;
float sumval = 0;
float svmean = 0;
float tmp = 0;
printf("Enter count : ");
scanf("%d", &n);
for (i = 0; i < n; ++i) {
scanf("%f", &tmp);
sumval = sumval + tmp;
}
svmean = sumval/n;
printf("%f \n",svmean);
return(0);
}
In your code, values[] array is not necessary to calculate output. Are you storing the values for any reason??..
You can allocate an array with variable size in the heap of the program like that:
#include <stdio.h>
int main(int argc, char **argv)
{
int i;
//Get the size of the array from input parameter
int n = atoi(argv[1]);
float sumval,svmean,tmp;
//Allocate the array of values
float *values = malloc(sizeof(float)*n);
// Initialize sumval
for(sumval=0,i=0;i<n;++i){
scanf("%f",&tmp);
values[i]=tmp;
sumval = sumval + values[i];
}
svmean = sumval/n;
printf("%f \n",svmean);
//Free it
free( values );
return(0);
}
You also need to initialize sumval to 0. The parameter of the size of the array is passed when launching the program (if you use an IDE you should check how it does that)

C - using dynamic arrays

I have a problem in C. This is the question:
Develop a C function ADDER that adds two integer arrays together. ADDER should have only two parameters, which are the two arrays to be added. The second array argument will hold the sum of arrays on exit. Both parameters should be passed by reference.
Write a C program to test the ADDER function with the call ADDER (A, A) where A is an array to be added to itself. Array A can be of any size with any values. Write, compile, and execute the program.
Explain the results of the program.
So far I have solved it this way and it works just fine:
#include <stdio.h>
// using namespace std;
const int SIZE = 5;
/* Adds two arrays and saves the result in b
* Assumes that b is larger than or equal to a in size
*/
void ADDER(int (&a)[SIZE], int (&b)[SIZE]) {
int aSize, bSize, i; /* variable declaration */
/* find out the sizes first */
aSize = sizeof (a) / sizeof (int);
bSize = sizeof (b) / sizeof (int);
/* add the values into b now */
for (i = 0; i < aSize; i++) {
b[i] = b[i] + a[i];
}
/* we have the sum at the end in b[] */
}
/* Test program for ADDER */
int main() {
int i; /* variable declaration */
int a[] = {1, 2, 3, 4, 5}; /* the first array */
/* add them now */
ADDER(a, a);
/* print results */
printf("\nThe sum of the two arrays is: ");
for (i = 0; i < SIZE; i++) {
printf("%d ", a[i]); /* print each element */
}
return 0;
}
The problem is, I have to use dynamic arrays and use malloc and realloc in the program to compute the size of the array on the fly. Instead of specifying the array size and the elements itself, I want the program to ask the user for input and the user enters the array and the size is determined there. It should all be dynamic. I do not know how this is done. Can anyone please help me out! thanks!
Also I have to explain how the array is added to itself the result is saved in "a" and the original array is lost replaced by the sum. how can I explain this?
Here is how your program would look like
int size; //global variable
void ADDER(int *a, int *b) {
int i;
for (i = 0; i < size; i++) {
b[i] += a[i];
}
}
int main(){
//ask the user to input the size and read the size
int *a = (int *)malloc(size*sizeof(int));
int *b = (int *)malloc(size*sizeof(int));
//fill up the elements
Adder(a,b);
//print out b
free(a->array);
free(b->array);
}
ALthough its not wise to use globals, the bottom line here is that adder somehow needs to know the size of the array and somehow you need to convey the size to the ADDER function. If that can't be done through parameters, you have to use globals.
Another option would be to use structures.
typedef struct myArray{
int *array;
int length;
}ARRAY;
void ADDER(ARRAY *a, ARRAY *b) {
int i;
for (i = 0; i < b->length; i++) {
b->array[i] += a->array[i];
}
}
int main(){
int size; //local variable
//ask the user to input the size and read into the 'size' variable
ARRAY *a, *b;
a->array = (int *)malloc(size*sizeof(int));
b->array = (int *)malloc(size*sizeof(int));
a->length = b->length = size;
//fill up the elements
Adder(a,b);
//print out b.array
free(a->array);
free(b->array);
}
How about something like this:
size_t length;
void ADDER(int *a, int *b)
{
for (int i = 0; i < length; i++)
{
/* Add the arrays */
}
}
int main()
{
/* Get the number of entries in the arrays from the user */
/* Store the result in the global variable "length" */
/* Check the "scanf" function for that */
int *a;
/* Allocate the array */
/* Remember that "malloc" wants the size in bytes, not number of items in the array */
/* Get all items for the array from the user */
/* Now add the array to itself */
ADDER(a, a);
/* Print the result */
/* Free the array, a very important step! */
}
As you can see it's not complete code, but gives hints about what should be done, and where. Hope it helps somewhat.
Edit 2 A note about the word "reference". The usage of references is different in C and C++. The way you declared your ADDER function, with int (&a)[SIZE] uses a C++ feature with the &. In plain C a "reference" is simply a pointer. See this SO question for some good answers about that part.
It is impossible to determine the size of a dynamically allocated array unless you allocate an additional element which works as a sentinel, i.e. contains a value that is never valid in real array elements. Another solution would be putting the number of elements in the first array element.
If you know the size at compile time (and according to your code you do so!), you can simply use the same constant when iterating over the array:
for (i = 0; i < SIZE; i++) {
b[i] += a[i];
}
You will have to read user input in a single int variable. After that you will have to allocate one more space to your int array and then proceed to insert the number to your array.
int main() {
int inpt; //user input.
int inptcnt=0; //amount of numbers given by the user.
char flag='y'; //use this char to know if the user wants to insert another number or no.
int *inptarray; //this pointer will be your int array.
inptarray = (int *) malloc (sizeof(int)); //Here you generate the first entry for your array.
if (inptarray == NULL) { //Never forget to check if Malloc and Realloc failed.
printf("Memory Error!!!\n);
exit(1);
}
while (flag == 'y') {
printf("Please enter a number:");
scanf("%d", inpt); //you ask from the user to input a number
inptcnt++; //You add one to the amount of numbers you have been given.
printf("\nIf you wish to enter another number as well please press 'y'. Press anything else if you dont:");
scanf(" %c", flag);
inptarray[inptcnt - 1] = inpt; //You add the number given by the user to your array.
if (flag != 'y') {
break;
} else {
realloc(inptarray, inptcnt * sizeof(int)); // Here you add space for the new entry to your array.
if (inptarray == NULL) { //Never forget to check if Malloc and Realloc failed.
printf("Memory Error!!!\n);
exit(1);
}
}
}
}
This is how you can generate an array of whatever size you need, according to user input.
You can access the size value of this array through the inptcnt variable. The number that is stored within this variable is the size of your array and the amount of user inputs you have. Also don't forget to call free(inptarray) after you are done using your array to free up the claimed memory.

Resources