Find the sum of numbers in an array C - c

I have researched for over an hour on this topic and I had no luck so I decided to go ahead and ask this question here. I have been figuring out how find the sum of 10 different numbers from the array after I type numbers on program. For example, it asks you to type 10 different numbers and they would be all added up after they are typed out in an array. Here is the code. The top part is function. The bottom part is from main(). Any helps would be heavily appreciated.
void addNum(int z[])
{
int sum = 0;
int i;
//scanf("%d", &z[i]);
sum = sum + z[i];
printf("\nThe sum of numbers you entered is %d.\n", sum);
}
...........
int z[10];
int i;
int num = 0;
printf("Please enter 10 different numbers: \n");
for(i = 0; i < 10; i++)
{
z[i] = num;
scanf("%d", &num);
}
printf("\nThe numbers you entered were: ");
for (i = 1; i <= 10; i++)
{
printf("%d ", z[i]);
}
printf("\n");
//scanf("%d", z[i]);
addNum(z[i]);

You should do the adding in your function
void addNum(int z[], int sizeOfArray)
{
int sum = 0;
//scanf("%d", &z[i]);
for(int i = 0; i < sizeOfArray; i++){
sum += z[i];
}
printf("\nThe sum of numbers you entered is %d.\n", sum);
}
Pass in the array in the main with the array size
addNum(z,10);

In your code use pass by reference and not pass by value.
When you call "addNum(z[i])" , i is 11 and what you are passing is z[11] which will be garbage at first place but you are passing only value of one variable which is not what you wanted.
What you want to pass is the address of the array either "z" or "&z[0]" . Along with the size of array, so the function knows how many member variables in array.

Related

In the code shown below, I'm not able to print the array in reverse order

In the code shown below, I'm not being able to print the array in reverse order. The rest of the code is working fine except for the reverse part. How can I solve this issue?
#include <stdio.h>
int main()
{
int arr[10]={1,2,3,4,5,6,7,8,9,10};
int i;
printf("Enter the values into the array and see them in normal and reverse order\n");
printf("------------------------------------------------------------------------\n");
printf("Enter the number of elements into the array\n");
scanf("%d", &i);
printf("Input %d elmements into the array:\n", i);
for (i = 0; i < 10; i ++)
{
printf("elemenet - %d: ", i);
scanf("%d", &arr[i]);
}
printf("\nThe values stored into the array are:\n");
for (i = 0; i < 10; i ++)
{
printf("%3d",arr[i] );
}
printf("\nThe values stored into the array in reverse order are:\n");
for (i = 0; i > 10; i --) \*something wrong here*\
{
printf("%5d",arr[i] );
}
printf("\n\n");
}
In particular the part from the code where the reverse of array is applied is shown below:
printf("\nThe values stored into the array in reverse order are:\n");
for (i = 0; i > 10; i --) \*something wrong here*\
{
printf("%5d",arr[i] );
}
Im not able to figure out how to reverse it. Your help would be appreciated.
Read your code:
for (i = 0; i > 10; i --)
it says: run from i=0 as long as i>10. this is of course not what you meant.
try changing it to
for (i = 9; i >= 0; i--)
If you want to print in the reverse order, you need to start i at the largest index and the loop condition should ensure that i is positive:
for (i=9; i>=0; i--)
{
printf("%5d",arr[i] );
}

C program to output the largest element of array with the index of the largest element of array

I'm taking my first ever programming class and most of it is self taught. So please bear with me.
After the users input numbers, such as 10, 20, 100, 3, 4 there should be an output to read
"the index of the largest elmeent in list1 array is _
The largest element in list1 array is 100" "
Here is my code so far. I know how to get the output of the largest array but not the first line or how to name my array. Thanks so much in advance.
#include<stdio.h>
int main()
{
int i;
float arr[5];
printf("Please enter five numbers:\n ");
for (i = 0; i < 5; ++i)
{
scanf_s("%f", &arr[i]);
}
for (i = 1; i < 5; ++i)
{
if (arr[0] < arr[i])
arr[0] = arr[i];
}
printf("Largest element = %.2f", arr[0]);
return 0;
}
This code here will give you the biggest element is the array but it also changes the order in which the elements were entered. Instead of taking the biggest element to the 0th position of the array,you can simply use an integer to store the index of the biggest element.Your program can be modified like this :
#include<stdio.h>
int main()
{
int i,temp=0;
float arr[5];
printf("Please enter five numbers:\n ");
for (i = 0; i < 5; ++i)
{
scanf_s("%f", &arr[i]);
}
for (i = 1; i < 5; ++i)
{
if (arr[temp] < arr[i])
temp=i;
}
printf("Largest element = %.2f", arr[temp]);
printf("Index = %d",temp);
return 0;
}
Hope the answer was useful.
Your approach to find the max element in an array is fine. But it alters the original array. If it okay with you, then go ahead with it, else if you would like to keep the array in tact as well as find the max element with the index, then check the code which I have attached below. If you intend to keep the methodology same, then just add a variable, which you should update as and when you find a higher number, as follows:
int max_index; //declare before
if (arr[0] < arr[i]) {
max_index = i;
arr[0] = arr[i];
}
If you are interested to keep the array unchanged and find out the max element with its index, the code would be as follows:
#include<stdio.h>
int main()
{
int i, max_index;
float arr[5], max;
printf("Please enter five numbers:\n ");
for (i = 0; i < 5; ++i)
{
scanf("%f", &arr[i]);
}
max = arr[0];//start off assuming that the 1st element is the max
for (i = 0; i < 5; i++)//now compare it with the rest of the array, updataing the max all along
{
if (arr[i] > max) {
max = arr[i];
max_index = i;
}
}
printf("Largest element = %.2f at index %d", max, max_index);
return 0;
}
Hope this helps.
You know, that you can get the element if you know its index. This means, you can store the index of the "known biggest" element, and you can refer to the biggest element using the stored index.
int imax = 0;
for (i = 1; i < 5; ++i)
{
if (arr[imax] < arr[i])
imax = i;
}
printf("Largest element = %.2f at index %i\n", arr[imax], imax);
.
use this code in place of last loop

Array additions and averages

So this weeks homework is to: 'Write a program that inputs 6 integers and puts them into an Array. The program
then prints out the following: A list of all Array elements, from 0 to 5 and the sum and
mean value of all elements. NB The mean value of the array elements will not
necessarily be an integer. In order to convert an integer into a real (float) use
casting:
To turn the integer ‘x’ into a float use float(x)
E.g.:
Average = float(sum)/number of elements ;
(In this case the number of elements is 6)'
Not quite sure what I am doing wrong here but my code seems to give back incorrect answers and I can't figure out why.
Any suggestions would be greatly appreciated. I feel like I am going to fail this module as I have struggled with it since the introduction of functions, etc.
Anyway, here is my code:
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main() {
int numArr[5];
int i, sum = 0;
float avg;
printf("\nEnter 6 elements : \n");
for (i = 0; i < 6; i++)
scanf("%d", &numArr[i]);
for (i = 0; i < 6; i++) {
sum = sum + i;
}
avg = sum /6;
printf("The sum is : %d", sum);
printf("The mean value is : %f", avg);
return 0;
}
'Write a program that inputs 6 integers
int numArr[5];
^^^^^
Change this loop
for (i = 0; i < 6; i++) {
sum = sum + i;
}
like
for (i = 0; i < 6; i++) {
sum = sum + numArr[I];
}
And change this statement
avg = sum /6;
the following way
avg = ( float )sum /6;
And you forgot to output all elements of the array.
Take into account that according to the C Standard the function main without parameters shall be declared like
int main( void )
and you may remove header <math.h> because neither declaration is used from this header in your program.
Your array isn't large enough to hold 6 numbers.
Change
int numArr[5];
to
int numArr[6];
Currently, you are accessing the array out-of-bunds, resulting in undefined behaviour.
There are couple other problems too:
1) You are not summing the array elements
2) You are doing integer division
Fix it, it'd look like:
#include<stdio.h>
#include<math.h>
int main(void) {
int numArr[6];
int i, sum = 0;
float avg;
printf("\nEnter 6 elements : \n");
for (i = 0; i < 6; i++)
scanf("%d", &numArr[i]);
for (i = 0; i < 6; i++) {
sum = sum + numArr[i]; /* was summing `i` instead of numArr[i] */
}
avg = sum /6.0; /* was doing integer division */
printf("The sum is : %d", sum);
printf("The mean value is : %f", avg);
return 0;
}
sum = sum + i;
should be
sum = sum + numArr[i];
Array elements should be added.
Later
avg = sum/6.0
for (i = 0; i < 6; i++) {
sum = sum + numArr[i];
}
avg = (float)sum /6;
Notice numArr[i]
int numArr[5];
should be
int numArr[6];
and
for (i = 0; i < 6; i++) {
sum = sum + i;
}
should be
for (i = 0; i < 6; i++) {
sum = sum + numArr[i];
}
and
avg = sum /6;
should be
avg = sum/6.0 //because division of integer by an integer results by integer value. So we divide integer with a float (6.0) value

Scramble numbers from array with numbers - C

I have been figuring out how to scramble numbers from array after user enters 10 different numbers by using rand(). It crushes when it arrives to adjust() function so feel free to point out my stupid mistake. Cheers. The top part is function, the bottom part is in main().
void adjust(int z[], int size)
{
int i, n, t;
for(i = 0; i < size; i++)
{
size = rand();
t = z[size];
z[size] = z[i];
z[i] = t;
}
printf("\nYour numbers have been scrambled and here they are: \n", t);
}
.....................
int z[10];
int i;
int num = 0;
printf("Please enter 10 different numbers: \n");
for(i = 0; i < 10; i++)
{
z[i] = num;
scanf("%d", &num);
}
printf("\nThe numbers you entered were: ");
for (i = num; i <= 10; i++)
{
printf("%d ", z[i]);
}
printf("\n");
addNum(z, 10);
adjust(z, 10);
return 0;
The rand() function returns a number between 0 and RAND_MAX.
Hence, the array index can go well beyond its range.
To get a random index within a range from 0 to N -1 , use rand() % N.
Another issue is that in your for loop, in adjust function, you are destroying the original value of 'size'. That contains the length of your array and is used to check the terminating condition of your for loop. Hence, do not modify 'size'. Use another variable to store your random index.
for(i = 0; i < size; i++)
{
n = rand() % size; // n is between 0 and size-1
t = z[n];
z[n] = z[i];
z[i] = t;
}
// For a better design move the following lines to a separate function
// that way adjust function just does the scrambling while another
// printing function prints out the array. Each function does only one thing.
printf("\nYour numbers have been scrambled and here they are: \n");
for( i = 0; i < size; i++)
{
printf("%d ", z[i]);
}

Average of prime numbers in an array

Well, the problem is the above. To sum it up, it compiles, but I guess my main idea is just wrong. What I'm trying to do with that code is:
I want the person to give us the elements of the array, how many he wants to (with a limit of a 100 elements).
After that, I'm checking what array positions are prime numbers.(ex: position 2,3,5,etc. Not the elements itself).
After that, I'm doing the average of the values in the prime numbers position.
That's it. Any ideas? Keep in mind that I'm on the first period of engineering, so I'm not the best in programming.
The code is below:
#include <stdio.h>
#include <windows.h>
int main(void)
{
int k, i, j, d, v[101], sum, prim, f;
float ave;
i = 0;
while ((i < 101) && (j != 0) )
{
i++;
printf("Set the value of the element %d => ", i);
scanf("%d", &v[i]);
printf("To stop press 0 => ");
scanf("%d", &j);
}
k = 0;
prim = 1;
f = i;
sum = 0;
while (f > 2)
{
if (i % (f - 1) == 0)
{
prim = 0;
}
else
{
k++;
sum = sum + v[f];
}
f = f - 1;
}
med = sum / k;
printf("%d, %d, %d", k, soma, i);
printf("The average is => %f \n", ave);
system("pause");
}
For those wondering, this is what i got after the editing in the correct answer:
int main(void)
{
int v[101];
int n = 0;
int k,j = 0;
int i=0;
int sum = 0;
while( i<100 )
{
i++;
printf ("Set the value of the element %d => ", i);
scanf ("%d", &v[i]);
int x,primo=1;
if (i>1){
for (x=2; x*x<=i; x++) {
if (i % x == 0) primo = 0;
}
if(primo==1)
{
sum = sum+ v[i];
n++;
}
}
printf ("To stop press 0 => ");
scanf ("%d", &j);
if(j == 0)
break;
}
float ave =(sum /n);
printf("%d, %d, %d", n,i,sum);
printf("The average is => %f \n", ave);
system("pause");
}
First lets make a readable method to test if a number is prime; this answer from another SO post gives us a good one:
int IsPrime(int number) {
int i;
for (i=2; i*i<=number; i++) {
if (number % i == 0) return 0;
}
return 1;
}
Second, let's clean your code, and compute a running sum of all the prime numbers encountered so far. Also, we will check the return values of scanf (but we should avoid scanf !)
And third, we add some indentation.
int main(void)
{
int n = 0;
int i = 0;
int j = 0;
int k = 0;
int sum = 0;
while( i<101 )
{
i++;
printf ("Set the value of the element %d => ", i);
if(scanf ("%d", &k) != 1)
continue;
if(is_prime(k))
{
sum += k;
++n;
}
printf ("To stop press 0 => ");
if(scanf ("%d", &j) == 1)
if(j == 0)
break;
}
float ave = sum / (double) n;
printf("The average is => %f \n", ave);
system("pause");
}
Well there are a few things to say. First the easy part: if the max number of integers allowed to read is 100 your variable "v" should be v[100]. This is not a char array, so this array don't need to have an extra element (v[100] will be an array of int that goes from v[0] to v[99]; adjust the loop limit too).
Also, you are checking if the number you have is prime in the variable f, but this var is assigned with the variable i and i is not an element of the array. You want to assign f something like v[i] (for i equal to 0 to the count of numbers read minus one). So you will need 2 loops: the one you are using now for checking if the number is prime, and another one that assigns v[i] to f.
Another thing to say is that you are calling scanf two times for reading, you could just read numbers and store it in a temporary variable. If this number is not zero then you store it in the array and keep reading, else you stop the reading.
By last I strongly recommend you set var names that make sense, use single letters only for the index variables; names like temp, array, max and countnumbers should appear in your code. It will be easier for you and everyone else to read your code, and you will reduce the number of mistakes.
Here's the solution to your problem. Very easy stuff.
/* C program to find average of all prime numbers from the inputted array(you can predefine it if you like.) */
#include <stdio.h>
#include <conio.h>
void main()
{
int ar[100], i, n, j, counter;
float avg = 0, numprime = 0;
printf("Enter the size of the array ");
scanf("%d", &n);
printf("\n Now enter the elements of the array");
for (i = 0; i < n; i++)
{
scanf("%d", &ar[i]);
}
printf(" Array is -");
for (i = 0; i < n; i++)
{
printf("\t %d", ar[i]);
}
printf("\n All the prime numbers in the array are -");
for (i = 0; i < n; i++)
{
counter = 0;
for (j = 2; j < ar[i]; j++)
{
if (ar[i] % j == 0)
{
counter = 1;
break;
}
}
if (counter == 0)
{
printf("\t %d", ar[i]);
numprime += 1;
avg += at[i];
}
}
avg /= numprime;
printf("Average of prime numbers is ℅f", avg);
getch();
}
You just need counter variables like above for all average computations. (Cause we need to know number of prime numbers in the array so we can divide the total of them and thus get average.) Don't worry about typecasting it is being done downwards... This solution works. I've written it myself.
Here is a cut at doing what you wanted. You don't need near the number of variables you originally had. Also, without knowing what you wanted to do with the prime number, I just output when a prime was encountered. Also as previously mentioned, using a function for checking prime really helps:
#include <stdio.h>
// #include <windows.h>
/* see: http://stackoverflow.com/questions/1538644/c-determine-if-a-number-is-prime */
int IsPrime(unsigned int number) {
if (number <= 1) return 0; // zero and one are not prime
unsigned int i;
for (i=2; i*i<=number; i++) {
if (number % i == 0) return 0;
}
return 1;
}
int main(void)
{
int i, v[101], sum, pcnt=0, psum=0;
float ave;
i=0;
printf ("\nEnter array values below, use [ctrl + d] to end input\n\n");
printf ("Set the value of the element %d => ", i);
while((i<101) && scanf ("%d", &v[i]) != EOF ){
sum += v[i];
if (IsPrime (v[i]))
psum += v[i], pcnt++;
i++;
printf ("Set the value of the element %d => ", i);
}
ave=(float)psum/pcnt;
printf("\n\n Number of elements : %d\n",i);
printf(" The sum of the elements: %d\n",sum);
printf(" The number of primes : %d\n",pcnt);
printf(" The average of primes : %f\n\n", ave);
return 0;
}
Sample Output:
Enter array values below, use [ctrl + d] to end input
Set the value of the element 0 => 10
Set the value of the element 1 => 20
Set the value of the element 2 => 30
Set the value of the element 3 => 40
Set the value of the element 4 => 51
Set the value of the element 5 => 11
Set the value of the element 6 => 37
Set the value of the element 7 =>
Number of elements : 7
The sum of the elements: 199
The number of primes : 2
The average of primes : 24.000000

Resources