Calculating sum of array - c

#include <stdio.h>
#include <stdlib.h>
int main(void) {
int numOfMeal, items[50];//, sum;
printf("Enter number of meals/snacks: ");
scanf("%d",&numOfMeal);
for(int i=1; i<=numOfMeal;i++)
{
printf("Enter kilojoules for item %d: ", i);
scanf("%d", &items[numOfMeal]);
}
printf("Your total kilojoules are: %d", items[numOfMeal]);
return EXIT_SUCCESS;
}
any ideas on how to calculate the sum of arrays, when i run this program it only displays the last kilojoule entered..

1.
You should run the loop from 0 to numOfMeal-1 because array indexing starts from the 0, not 1. If you are accessing the nth element that is a segmentation fault.
2.
The second problem in your code is that you are not taking the input values in the array. Your loop is, again and again, overwriting the items[numOfMeal] which is the last element in your array.
Write your code as below:
int numOfMeal, items[50],sum=0;
printf("Enter number of meals/snacks: ");
scanf("%d",&numOfMeal);
for(int i=0; i<numOfMeal;i++) // run loop from 0 to numOfMeal-1
{
printf("Enter kilojoules for item %d: ", i);
scanf("%d", &items[i]); // take the input at ith position in the array
sum+=items[i]; // sum them
}
printf("Your total kilojoules are: %d", sum); // print the final result
The short code for this can be
int numOfMeal, item, sum=0;
scanf("%d",&numOfMeal);
for(int i=0; i<numOfMeal;i++){
scanf("%d", &item);
sum+=item;
}
printf("Your total kilojoules are: %d", sum);
In this code I am not storing the value in the array, just saving it temporarily in the variable and add it to sum variable.

1) change your for loop. indexes of array start at 0. change i = 1 to i = 0 and i <= numOfMeal to i < numOfMeal
2) you have to calculate sum of array elements in loop
...
int result = 0;
for (int i = 0; i < numOfMeal; i++)
{
...
result += items[i];
}
printf("Your total kilojoules are: %d", result);
...

Related

Find the mistake in the code — we have to print the sum of elements of the array of any size

The elements of the array have to be taken as input from the user. Here I am using an array of size 10. I am getting the sum as 0 if I initialized it with sum = 0; while declaring, and if I didn't, I am getting a garbage value.
Here is the code:
#include <stdio.h>
int main(void)
{
int barray[10], i=0, sum=0;
for(i=0;i<10;i++ ){
printf("Enter the value for barray[%d] element of the array : ",i);
scanf("%d", &barray[i]);
}
while(i >=0 && i<10)
{
sum += barray[i];
i++;
}
printf("The sum of the elements of the array is %d", sum);
}
The problem with your code is that i is not a variable declared in the scope of the for loop but in the scope of main, so when the for loop is done i=10 and then the contents of the while loop are skipped as the condition for i to be greater than 0 and less than 10 are never met.
To fix this you should set i to zero after the for loop
scanf("%d", &barray[i]);
}
i = 0; // add this
while(i >=0 && i<10)
{
or change the while loop to a for loop like the first one. Though I would recommend as good practice and for cleaner code to declare the iterator variable inside the context of the for loop unless you need to access it outside of it, like so.
int main(void)
{
int barray[10], sum=0;
for (int i = 0; i < 10; i++) {
printf("Enter the value for barray[%d] element of the array : ", i);
scanf("%d", &barray[i]);
}
for (int i = 0; i < 10; i++) {
sum += barray[i];
}
printf("The sum of the elements of the array is %d", sum);
}

find the most frequent number in an array

I've recently started learning C and I ran into this small test.
Make a code which reads 10 numbers from a user.
Print the Largest & Smallest entered values then print the most frequent number.
Making everything was simple for me but the most-frequent number is driving me crazy, I've searched for awhile and couldn't find any clear answers.
The code I wrote
#include <stdio.h>
#include <stdlib.h>
int main()
{
int hi[10], i=0, largest, smallest;
while(i<10)
{
printf("Enter a number:");
scanf("%d", &hi[i]);
i++;
}
smallest = hi[0];
largest = hi[0];
printf("Entered Numbers: ");
while(i!=0)
{
if(hi[10-i] < smallest) { smallest = hi[10-i]; }
if(hi[10-i] > largest) { largest = hi[10-i]; }
printf("%d | ", hi[10-i]);
i--;
}
printf("\nLargest number is = %d || Smallest number is = %d", largest, smallest);
return 0;
}
The only idea I thought of was:
Making another array.
Getting value of [i] in the original array.
Compare [i] with rest of values of original array (if they are equal or not).
Increment the value of the other array if they are equal.
Check largest value in the other array and that should be most frequent number.
Now, I know the order of most frequent element and how many times that element was entered.
Using a hashmap would be more efficient. There you can use the input number as key and set the value to 1. When a new number was given by the user, you just have to check wether the new number is already in the map. If so, you set the value to two, otherwise you add the new number with the value 1.
Piggy backing on what Markus said, a hash map really is ideal for a universal solution so you can keep the asymptotic time down, but since you're only doing an array of 10, using a 2D array to store the frequency will work just fine.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int hi[10][2], i=0,j=0,largest, smallest;
while(i<10)
{
printf("Enter a number:");
scanf("%d", &hi[i][0]);
i++;
}
smallest = hi[0][0];
largest = hi[0][0];
printf("Entered Numbers: ");
while(i!=0)
{
hi[10-i][1] = 0;
if(hi[10-i][0] < smallest) { smallest = hi[10-i][0]; }
if(hi[10-i][0] > largest) { largest = hi[10-i][0]; }
printf("%d | ", hi[10-i][0]);
i--;
}
int most_freq = 0;
for (i = 0; i < 10; i++){
for (j = 0; j < 10; j++){
if(hi[i][0] == hi[j][0]){
hi[i][1]++;
if (hi[i][1] > most_freq){
most_freq = hi[i][0];
}
}
}
}
printf("\nLargest number is = %d || Smallest number is = %d", largest, smallest);
printf("\nMost frequent is = %d\n", most_freq);
return 0;
}

C - how to display the numbers in an array that are lower than the average value of the numbers in the array

#include <stdio.h>
#include <stdlib.h>
void main()
{
int i=0;
int ray[20];
float sum=0.00, average;
for (i=0; i<20; i++)
{
printf("Enter integer #%d",i+1);
scanf ("%d", &ray[i]);
sum=(sum+ray[i]);
}
average=(sum/20);
printf("Average = %.2f", average);
if (ray[i] < average)
{
printf("The followiing values are less than the average: %d", ray[i]);
}
system("pause");
}
The code runs fine and gives the correct average of the integers entered but the values that are less than the average comes out as -858993460
You are trying to print out ray[i], but i is currently 20which is outside the index of your array. Did you mean to copy your for loop around that if statement?
#include <stdio.h>
#include <stdlib.h>
void main()
{
int i=0;
int ray[20];
float sum=0.00, average;
for (i=0; i<20; i++)
{
printf("Enter integer #%d: ",i+1);
scanf ("%d", &ray[i]);
sum=(sum+ray[i]);
average=(sum/20);
if (ray[i] < average)
{
printf("The followiing values are less than the average: %d", ray[i]);
}
}
printf("Average = %.2f", average);
system("pause");
}
This gives the "the following integers are below the average" part after each value that is lower than the then average, but I need it to show the values which are below the average together at the end.
The out-of-index issue
As the others have already pointed, your index is out of bounds.
That happens because you've iterated for (i=0; i < 20; i++), which means once you left the for statement you were at i == 20. Your array was allocated with 20 positions, so you can access it from index 0 to 19. The awkward value you get is given because you are accessing "trash", or in other words, invalid positions with unpredictable (or almost) values.
The algorithm issue
Ok, once you got that index thing right, you still need an algorithm that displays the numbers that are lower than the average. You can't just copy your if statement into the loop because you only know the true average value once you've iterated through all of the values (which you are doing just fine).
So what you want is another loop that iterates throughout the array and that if statement inside of it (well, there are other ways to do it without running all of the values again, like sorting the array)
So, this is the algorithm I'll propose you
#include <stdio.h>
#include <stdlib.h>
#define array_size 20
void main()
{
int i;
int ray[array_size];
int sum=0;
float average;
for (i=0; i<array_size; i++)
{
printf("Enter integer #%d: ",i+1);
scanf ("%d", &ray[i]);
sum += ray[i];
}
average=(sum/(float)array_size);
printf("Average = %.2f\n", average);
printf("The following values are less than the average: ");
for (i = 0; i < array_size; i++)
{
if (ray[i] < average)
{
printf("%d ", ray[i]);
}
}
system("pause");
}
This Part in Your Code:
for (i=0; i<20; i++)
{
printf("Enter integer #%d",i+1);
scanf ("%d", &ray[i]);
sum=(sum+ray[i]);
}
//Now i = 20,that is why it left loop
average=(sum/20);
printf("Average = %.2f", average);
if (ray[i] < average) //You are saying if ray[20]<average
{
printf("The following values are less than the average: %d", ray[i]);
}
Now ray[20] is outside the scope because there are 20 elements and array index starts from 0 and goes on to 19, so ray[20] is out of bound access.
I highly recommend you to see this question for better understaning How dangerous is it to access an array out of bounds?.
Secondly You want to print all ray[i] where ray[i] < average so you should run a loop like
printf("The following values are less than the average:");
for(i = 0; i<20; i++) // i starts from 0 and increase with run of loop
// and loop stops when i>19 so you are not
// accessing forbidden area.
{
if (ray[i] < average){ //check if ray[i] is less than average
printf("%d\n", ray[i])
}
}
All That makes :
#include <stdio.h>
#include <stdlib.h>
void main()
{
int i=0;
int ray[20];
float sum=0.00, average;
for (i=0; i<20; i++)
{
printf("Enter integer #%d",i+1);
scanf ("%d", &ray[i]);
sum=(sum+ray[i]);
}
average=(sum/20);
printf("Average = %.2f", average);
printf("The following values are less than the average:");
for(i = 0; i<20; i++) // i starts from 0 and increase with run of loop
// and loop stops when i>19 so you are not
// accessing forbidden area.
{
if (ray[i] < average){ //check if ray[i] is less than average
printf("%d\n", ray[i]);
}
}
system("pause");
}

How to get the value of the last element of an array?

Observe the following code. I want to divide the amount by the value of the last element in the array. I have tried in the following way but it is not working. Can anyone tell me what is the proper way to do it?
#include<stdio.h>
int main()
{
int i, j, k, noteNumber, array[100], amount, result;
printf("Enter the number of the notes: \n");
scanf("%d", &noteNumber);
printf("Enter the value of %d notes: \n", noteNumber);
for(i = 0; i < noteNumber; i++){
scanf("%d", &array[i]);
}
printf("Enter the amount: \n");
scanf("%d", &amount);
i = j;
if(amount / array[j] == 0){
printf("Minimum %d number of is needed", (amount/array[j]));
printf("The value of each note is %d", array[j]);
}
}
As I can see
i = j;
is wrong as you're using the value of an uninitialized variable to assign to another. This does not make any sense and can lead to undefined behavior.
C arrays use 0-based indexing, so for an array of size n, the last index would be n-1.
That said, never use an unbound index for a statically defined array, always perform the bound checking before using the index.
If noteNumber is the size of the array, then the last Element will be
array[noteNumber - 1]
As far as I can see, j isn't even initialized?
You are having a line
i = j;
j is not even initialized so you are doing a mistake here , maybe what
you wanted was
j = i - 1
As i would have incremented to noteNumber in your for loop and array with number of elements n has last element index n-1 because index starts from 0 rather than 1.
So Proper Code Would Be
#include<stdio.h>
int main(){
int i, j, k, noteNumber, array[100], amount, result;
printf("Enter the number of the notes: \n");
scanf("%d", &noteNumber);
printf("Enter the value of %d notes: \n", noteNumber);
for(i = 0; i < noteNumber; i++){
scanf("%d", &array[i]);
}
printf("Enter the amount: \n");
scanf("%d", &amount);
j = i - 1; // Line Changed
if(amount / array[j] == 0){
printf("Minimum %d number of is needed", (amount/array[j]));
printf("The value of each note is %d", array[j]);
}
}

calculating and finding difference in pairs of values in c

I really need help with this question.
Write a program that accepts six(6)
pairs of values from the user and then
calculates and stores the difference
of each pair of values in an array.The
array of calculated values should then
be sorted into ascending order and
printed on the screen.
I got through with inputting the six pairs of values, what I'm getting trouble with is the difference and storing in ascending order.
Any help given would be greatly appreciated.
#include <stdio.h>
main()
{
int arr[12], num1, num2, i;
for (i = 1; i < 7; i++) {
printf("Enter first number for pair ");
scanf("%d", &num1);
printf("Enter second number for pair ");
scanf("%d", &num2);
}
if (num1 > num2)
printf("arr[i-1=num1-num2 ");
else
printf("arr[i-1]=num2-num1 ");
{
for (i = 1; 1 < 7; i++)
printf("%7d\n", arr[i]);
}
return (0);
}
You need to check the difference immedialy after you read both values and store the value.
#include <stdio.h>
main()
{
int arr[7], num1, num2, i;
for (i = 0; i < 7; i++) {
printf("Enter first number for pair ");
scanf("%d", &num1);
printf("Enter second number for pair ");
scanf("%d", &num2);
//check differences now
if(num1>num2)
{
arr[i]=num1-num2;
}
else
{
arr[i]=num2-num1;
}
}
}
For the ordering of the vector, you could use a bubble-sort algorythm.
http://www.algorithmist.com/index.php/Bubble_sort.c
The reason for changing the vector and for limits is because vector positions go from 0 to n and not 1 to n, meaning that the for should go from 0 to 6 ( < 7 or <= 6 ).

Resources