How can I print highest value in an array? - c

I have scanf in a array I need to print the highest array stored
the problem is it print 0 every print
#include <stdio.h>
int main()
{
int n; // To input how many set of number to be entered
int order_number; // To count the numbers being entered
int length; // To count how many numbers in the array to be used in the last print
int max; // max computations later in last print
float num[100], sum = 0.0, average;
printf("Enter how numbers to be counted: ");
scanf("%d", &n); // asks the user how many numbers to be entered
while (n > 100 || n < 1)
{
printf("The entered number could not handle 100 above or below 1\n"); // shows if the user enters below 1 and above 100
printf("Please enter a number again: "); // asks the user to enter a number again
scanf("%d", &n); // asks the user how many numbers to be entered
}
for (order_number = 0; order_number < n; ++order_number) // loop syntax for counting numbers being entered
{
printf("%d. Enter number: ", order_number + 1); // prints the counting number being entered
scanf("%f", &num[order_number]); // asks the user for a number then store to the array
sum += num[order_number]; // adds all the number from the array
}
average = sum / n; // computes the average by adding a group of numbers and then dividing by the count of those numbers.
printf("The average is %.2f\n", average);
// Problem start here
length = sizeof(num) / sizeof(num[0]);
max = num[100];
for (int i = 0; i < length; i++)
{
if (num[i] > max)
max = num[i];
}
printf("Largest element present in given array: %d\n", max);
return 0;
}

#include <stdio.h>
int main()
{
int n; // To input how many set of number to be entered
int order_number; // To count the numbers being entered
int length; // To count how many numbers in the array to be used in the last print
int max; // max computations later in last print
float num[100], sum = 0.0, average;
printf("Enter how numbers to be counted: ");
scanf("%d", &n); // asks the user how many numbers to be entered
while (n > 100 || n < 1)
{
printf("The entered number could not handle 100 above or below 1\n"); // shows if the user enters below 1 and above 100
printf("Please enter a number again: "); // asks the user to enter a number again
scanf("%d", &n); // asks the user how many numbers to be entered
}
for (order_number = 0; order_number < n; ++order_number) // loop syntax for counting numbers being entered
{
printf("%d. Enter number: ", order_number + 1); // prints the counting number being entered
scanf("%f", &num[order_number]); // asks the user for a number then store to the array
sum += num[order_number]; // adds all the number from the array
}
average = sum / n; // computes the average by adding a group of numbers and then dividing by the count of those numbers.
printf("The average is %.2f\n", average);
max = num[0];
for (int i = 1; i < n; i++) // computation on finding the highest number in the array using loop
{
if (num[i] > max)
max = num[i];
}
printf("The largest number in the array is %d\n", max);
return 0;
}

max = num[100]; - you are looking at the 101st element of a 100 element array, indexed from zero. If you're lucky, you don't get a segmentation fault or some other memory error, since you're looking past the end of the array, but you're still going to get something random that happened to be in that memory location.
To iterate over the array, you then use all elements of the array, since you limit the loop by length - rather than 'n', which you've set to the number of used elements in the array. So you're also including length - n elements at the end that were never initialised to a useful value.

Related

Calculating average of pair numbers

Hello I have been working on a program in C that calculates numbers and it gives me back an average. Now I'm having issues implementing code that will ask a user to enter any number of pairs and calculate the average. Below is the code that I been working on. I'm able to change the while (count < 5)to 10 to get more pairs, but my goal is to ask a user to input any PAIR and THEN calculate the average (re iterating).
#include <stdio.h>
int main () {
int count;
double avg, value, weight, sum, sumw;
count = 0;
sum = 0;
sumw = 0;
avg = 0.0;
while (count < 5) {
printf("Enter value and it's weight:");
scanf("%lf %lf", &value, &weight);
if (weight >= 0) {
sumw = sumw + weight;
sum = sum + value * weight;
count = count + 1;
}
else { printf("weight must be positive\n");
}
}
avg = sum / sumw;
printf("average is %lf\n " , avg );
return 0;
}
**Second part ** On this on I'm not too sure how to make it to PAIRS plus calculate avg. ej: 2 1 , 2 4 , 4 4 etc.
#include<stdio.h>
void main()
{
int i,n,Sum=0,numbers;
float Average;
printf("\nPlease Enter How many pairs do you want?\n");
scanf("%d",&n);
printf("\nPlease Enter the elements one by one\n");
for(i=0;i<n;++i)
{
scanf("%d",&numbers);
Sum = Sum +numbers;
}
Average = Sum/n;
printf("\nAverage of the %d Numbers = %.2f",n, Average);
return 0;
}
but my goal is to ask a user to input any PAIR and THEN calculate the
Well, then you need to store the values somewhere. Recommendation: Have a struct for:
typedef struct
{
double value;
double weight;
} Pair;
Then as soon as you have got number of pairs to read from user, create an array of pairs:
Pair* pairs = malloc(number * sizeof(*pairs));
Very important: Every malloc should go with a free to avoid memory leaks. General recommendation: plan the free immediately when or even before mallocing.
Now inside your loop, you can fill the pairs:
scanf("%lf %lf", &pairs[i].value, &pairs[weight].weight);
Analogously, you can then use the pairs in the array in next loop or for whatever other purpose.
Side note:
if (weight >= 0)
{
// ...
}
else
{
// printf("weight must be positive\n");
}
If user gave negative input, you'll be just skipping some values (or or as in loop proposed, still retain the negative values!).
You might instead read inside a nested loop until value is valid. Additionally consider user providing non-numeric input, too! In that case, you couldn't read a double at all. So general rule is: Always check the result of scanf:
if(scanf("%lf %lf", &value, &weight) != 2 || value < 0 || weight < 0)
// ^
// assuming negative value not desired either
{
// user input was invalid!!!
}

C: Unable to use modulus operators to break down change into denominations, storing into an array and print the output to the user

I'm attempting to write a program in which:
The user inputs the cost of an item
The user inputs the amount they paid for the item
The program determines if the user is owed any change
The program calculates the amount of change owed
The program uses the modulus operator to break the amount of change down into coin denominations
The program stores the change and coin denominations into an array This is the first bit at which I'm getting stuck
The program displays the amount of change in coin denominations to the user
The purpose is to use an array to hold the values of the coins, so I "can write a general purpose change calculator that can be used for any coinage by changing the contents of the array".
Here is my code:
void vendingMachine()
{
// Declarations
#define ARRAY_LENGTH 6
int itemCost;
int amountEntered;
int fifty, twenty, ten, five, two, one;
int remainder;
// User input
printf("Please enter the cost of the item in pence: ");
scanf_s("%d", &itemCost);
while (itemCost <= 0 || itemCost > 99)
{
printf("You've entered an invalid amount. Please enter an amount between 1p and 99p: ");
scanf_s("%d", &itemCost);
}
printf("Please enter the amount entered into the machine in pence: ");
scanf_s("%d", &amountEntered);
while (amountEntered <= 0 || amountEntered > 100)
{
printf("You've entered an invalid amount. Please enter an amount between 1p and 100p: ");
scanf_s("%d", &amountEntered);
}
while (amountEntered < itemCost)
{
printf("You've entered an invalid amount. Please enter an amount equal to or higher than the cost of the item: ");
scanf_s("%d", &amountEntered);
}
// Program to determine if the customer is owed any change and, if so, how much is owed
if (amountEntered == itemCost)
{
printf("No change is owed to the customer");
}
else if (amountEntered > itemCost)
{
int change = amountEntered - itemCost;
printf("The amount of change owed to the customer is: %d pence, broken down as follows: \n", change);
fifty = change / 50;
remainder = change % 50;
twenty = remainder / 20;
remainder = remainder % 20;
ten = remainder / 10;
remainder = remainder % 10;
five = remainder / 5;
remainder = remainder % 5;
two = remainder / 2;
remainder = remainder % 2;
one = remainder;
// Program to store the change in an array
int count[ARRAY_LENGTH];
count[0] = fifty;
count[1] = twenty;
count[2] = ten;
count[3] = five;
count[4] = two;
count[5] = one;
for (int i = 0; i < ARRAY_LENGTH; i++)
{
count[i] = 0;
}
for (int i = 0; i < ARRAY_LENGTH; i++)
{
printf("The number of %d coins is: %d\n", //I don't know what to do here);
}
}
}
Store the type of coins in an array as well, e.g.
const int coins[ARRAY_LENGTH] = { 50, 20, 10, 5, 2, 1 };
Then you can easily refer to them in your loop:
printf("The number of %d coins is: %d\n", coins[i], count[i]);
This also allows you to perform your modulo calculations in a loop.
I am not sure what you are trying to achieve here:
The following piece of (your) code sets the values of count from index 0 to index 5, starting from fifty to one..
int count[ARRAY_LENGTH];
count[0] = fifty;
count[1] = twenty;
count[2] = ten;
count[3] = five;
count[4] = two;
count[5] = one;
Then here, you are overwriting those with 0 in the for loop.
for (int i = 0; i < ARRAY_LENGTH; i++)
{
count[i] = 0;
}
So above loop is not required, or at least must not be placed after you have assigned values of fifty, twenty, ten, five, two and one to count array indices.
I guess you are trying to print them? You don't have to use a loop here:
// Doing it the newbie-way:
printf("The number of coins of 50 are: %d\n", count[0]);
printf("The number of coins of 20 are: %d\n", count[1]);
printf("The number of coins of 10 are: %d\n", count[2]);
printf("The number of coins of 5 are: %d\n", count[3]);
printf("The number of coins of 2 are: %d\n", count[4]);
printf("The number of coins of 1 are: %d\n", count[5]);

Incorrect output for a particular code. (Maximum, minimum, grade_scanner)

I've been trying to figure this out the last few days, but no luck. The objective is to find the sum, average, minimum, and maximum grades and display them.
Here is my code, everything except minimum, maximum and grade input seem to work
// Includes printf and scanf functions
#include <stdio.h>
int main(void) {
unsigned int counter; // number of grade to be entered next
int grade; // grade value
int total; // sum of grades entered by user
float average; // average of grades
int maxi; // Max grade
int mini; // min grade
int i;
int max;
int min;
maxi = 1;
mini = 1;
printf("Enter number of grades: "); // User enters number of grades
scanf("%d", &counter); // Countss number of grades
//scanf("%d%d", &min, &max);
for (i = 1; i <= counter; i++) {
printf("Enter grade %d: ", i); // User enters grade
scanf("%d", &grade); // Counts grades
//scanf("%d",&counter);
if (grade < 0 || grade > 100) {
printf("Please enter a number between 0 and 100!\n"); // Lets user know if input is invalid
i--;
break;
}
else {
total = total + grade;
average = (float)total / counter; // NOTE: integer division, not decimal
}
}
max = (grade < maxi) ? maxi : grade;
min = (grade > mini) ? mini : grade;
printf("Class average is: %.3f\n", average); // Displays average
printf("Your maximum grade is %d\n", max); // Displays Max
printf("Your minimum grade is %d\n", min); // Displays minimum
printf("Sum: %d\n", total); // Displays total
}
Output:
Enter number of grades: 2
5
7
Enter grade 1: 4
Enter grade 2: 3
Class average is: 3.500
Your maximum grade is 3
Your minimum grade is 1
Sum: 7
For some reason when I start the program, I have to enter a few numbers, in this case 5 & 7 before it prompts me to "Enter grade" then from there it calculates everything. Also, it seems that the Maximum is always the last grade that I enter and shows 1 as the minimum when no where in the input is 1. I am supposed to use a conditional operator for the max/min, I tried looking it up and reading the book, but they just use letters like a,b,c, etc. Which just confused me so I'm not sure if I did it wrong.
Could that be what is messing everything up? If it isn't what am I doing wrong?
Another thing is I'm thinking I need a While loop if I want to make the counter have an input from 1-100, is that right?
Edit: just realized I had to remove the scanf for max and min. Taht's why I had to inptu 2 nubmers first
There are two major problems, as I see it
The variable total is not initialized, so the first occurrence of total = total + grade; would invoke undefined behaviour.
You have to initialize it explicitly to 0.
The same variable grade is used for holding the repeated input. After the loop, grade will only hold the last input value.
You need to either use an array for storing inputs and comparison, or, compare and update the min and max as you go, inside the loop.
For future references, please seperate your code in different functions or add comments, since analyzing an unfamiliar code always takes much time.
min: Your problem here lies, that you're initializing your min value with 1. That value is most of the time below your input grades. If you want to initialize it, you should use a high number.
For example:
#include <limits.h>
int min = INT_MAX;
max: Your "grade" will be always the last typed grade, which you scanned. That's not what you want. It would be good, to save all values, which you get as input in an array or a list.
Also your codesnippet at the end
max = (grade<maxi) ? maxi : grade;
min = (grade>mini) ? mini : grade;
will just compare one grade. You need to compare all values, which you entered.
You could just put them in the for-loop.
gradeinput: You need to temporarily save your inputs in a datastructure like an array/list to use them in your program.
int x[counter];
for (i = 1; i <= counter; i++) {
printf("Enter grade %d: ", i);
x[i]=scanf("%d", &grade);
}
.. have to enter a few numbers, in this case 5 & 7 before it prompts me to "Enter grade"
This happens because OP's stdout is buffered and not one character at a time.
To insure output is seen before the scanf(), use fflush().
See What are the rules of automatic flushing stdout buffer in C?
printf("Enter number of grades: ");
fflush(stdout); // add
scanf("%d", &counter);
Rather than set the min = 1, set to a great value
maxi = 1;
mini = 1;
maxi = 0;
mini = 100;
// or
maxi = INT_MIN;
mini = INT_MAX;
Move the test for min/max in the loop to test each value and fold maxi, max into the same variable.
if (max > grade) max = grade;
if (min < grade) min = grade;
The first total + grade is a problem as total is uninitialized.
// int total; // sum of grades entered by user
int total = 0; // sum of grades entered by user
Unnecessary to calculate average each time though the loop. Sufficient to do so afterward.
Style: After the break; the else is not needed.
Good that code tests user input range. Yet the i-- is incorrect. If code is to break, just break. If code it to try again, the i-- makes sense, but then code should continue.
The comment // NOTE: integer division, not decimal is incorrect as (float) total / counter is FP division.
if (grade < 0 || grade > 100) {
printf("Please enter a number between 0 and 100!\n");
i--;
continue;
}
total = total + grade;
} // end for
average = (float) total / counter;
In general, casting should be avoided.
Advanced issue: Consider the situation if later on code was improved to handle a wider range of integers and used higher precision FP math.
The 1st form causes total to become a float (this could lose precision) and perhaps use float to calculate the quotient, even if average was a double. Of course the (float) cast could be edited to (double) as part of the upgrade, but that is a common failure about updates. Types may be changed, but their affected object uses are not fully vetted.
The 2nd form below causes total to become the same type as average and use the matching math for the type. Reduced changed needed as the types change. This form is also easier to review as one does not need to go back and check the FP type of average to see if a cast to float, double or even long double was needed.
average = (float) total / counter;
// or
average = total;
average /= counter;
For some reason when I start the program, I have to enter a few numbers, in this case 5 & 7 before it prompts me to "Enter grade"
You have two scanf before "Enter grade"
scanf("%d", &counter);
scanf("%d%d", &min, &max);
#include <stdio.h>
int main(void) {
int counter; // number of grade to be entered next
int grade; // grade value
int total=0; // sum of grades entered by user
float average; // average of grades
int i;
int max;
int min;
printf("Enter number of grades: "); // User enters number of grades
scanf("%d", &counter); // Countss number of grades
for (i = 1; i <= counter; i++) {
printf("Enter grade %d: ", i); // User enters grade
scanf("%d", &grade); // Counts grades
if (grade < 0 || grade > 100) {
printf("Please enter a number between 0 and 100!\n"); // Lets user know if input is invalid
i--;
} else {
if(i==1){
max = grade;
min = grade;
}
else{
max = (grade < max) ? max : grade;
min = (grade > min) ? min : grade;
}
total = total + grade;
average = (float) total / counter; // NOTE: integer division, not decimal
}
}
printf("Class average is: %.3f\n", average); // Displays average
printf("Your maximum grade is %d\n", max); // Displays Max
printf("Your minimum grade is %d\n", min); // Displays minimum
printf("Sum: %d\n", total); // Displays total
}
I've edited your Code as there were some mistakes. First, you were not initialising the total, which may make it take some garbage value. The second one is no need of using break as you are reducing the value of i.The third one is that you are updating the min and max outside the for loop, where the value of grade will be the last entered grade. And maxi and mini are not at all needed. The code was running perfectly without waiting for dummy values. Cheers!

Calculating sum of array

#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);
...

Calculating the average of user inputs in c

disclaimer: I'm new to programming
I'm working on this problem
so far ive written this which takes user inputs and calculates an average based on them
#include <stdio.h>
int main()
{
int n, i;
float num[100], sum = 0.0, average;
for(i = 0; i < n; ++i)
{
printf("%d. Enter number: ", i+1);
scanf("%f", &num[i]);
sum += num[i];
}
average = sum / n;
printf("Average = %.2f", average);
return 0;
}
I'd like the user to enter -1 to indicate that they are done entering data; I can't figure out how to do that. so if possible can someone explain or give me an idea as to how to do it
Thank you!
#include <stdio.h>
int main()
{
int i = 0;
float num[100], sum = 0.0, average;
float x = 0.0;
while(1) {
printf("%d. Enter number: ", i+1);
scanf("%f", &x);
if(x == -1)
break;
num[i] = x;
sum += num[i];
i++;
}
average = sum / i;
printf("\n Average = %.2f", average);
return 0;
}
There is no need for the array num[] if you don't want the data to be used later.
Hope this will help.!!
You just need the average. No need to store all the entered numbers for that.
You just need the number inputs before the -1 stored in a variable, say count which is incremented upon each iteration of the loop and a variable like sum to hold the sum of all numbers entered so far.
In your program, you have not initialised n before using it. n has only garbage whose value in indeterminate.
You don't even need the average variable for that. You can just print out sum/count while printing the average.
Do
int count=0;
float num, sum = 0;
while(scanf("%f", &num)==1 && num!=-1)
{
count++;
sum += num;
}
to stop reading at -1.
There is no need to declare an array to store entered numbers. All you need is to check whether next entered number is equal to -1 and if not then to add it to the sum.
Pay attention to that according to the assignment the user has to enter integer numbers. The average can be calculated as an integer number or as a float number.
The program can look the following way
#include <stdio.h>
int main( void )
{
unsigned int n = 0;
unsigned long long int sum = 0;
printf("Enter a sequence of positive numbers (-1 - exit): ");
for (unsigned int num; scanf("%u", &num) == 1 && num != -1; )
{
++n;
sum += num;
}
if (n)
{
printf("\nAverage = %llu\n", sum / n);
}
else
{
puts("You did not eneter a number. Try next time.");
}
return 0;
}
The program output might look like
Enter a sequence of positive numbers (-1 - exit): 1 2 3 4 5 6 7 8 9 10 -1
Average = 5
If you need to calculate the average as a float number then just declare the variable sum as having the type double and use the corresponding format specifier in the printf statement to output the average.

Resources