Program doesn't work with 10 values in array - c

Basically, the max size of the array is 10 and the user is allowed to enter up to 10 values. If the user enters -1 or 0, before entering the ten values, then the loop stops and goes to the next loop. My problem is is that it works perfectly UNTIL I enter 10 values. The result will divide by 9 instead of 10 and print that there are 9 values in the array.
#include <stdio.h>
int main(void)
{
float numbers[10];
int i;
int n;
int count =0;
for(i = 0; i<10; i++)
{
scanf("%f", &numbers[i]);
if(numbers[i] == -1)
break;
if(numbers[i] == 0)
break;
count++;
}
n = count-1;
float sum = 0;
float average;
for(i = 0; i<=n; i++)
{
sum = sum + numbers[i];
}
average = sum/count;
printf("The average price of the %d products is %.2f.\n", count, average);
return 0;
} //this is the fixed solution.

You should not write n=count-1; write n=count; instead. And move count++ to the end of loop.
#include <stdio.h>
int main(void)
{
float numbers[10];
int i;
int n;
int count =0;
for(i = 0; i<10; i++)
{
scanf("%f", &numbers[i]);
if(numbers[i] == -1)
break;
if(numbers[i] == 0)
break;
count++;
}
n = count;
float sum = 0;
float average;
for(i = 0; i<n; i++)
{
sum = sum + numbers[i];
}
average = sum/a;
printf("The average price of the %d products is %.2f.\n", n, average);
return 0;
}

I'm pretty sure it is because of this line
n = count-1
Can you explain why you are subtracting 1? In the case where you input 10 numbers, count will equal 10. After subtracting 1 you will then only iterate thru the first 9 indexes in the array.
If you need to subtract 1 (to account for the user inputting a 0 or -1), then change the condition in the last for loop to be <= instead.
for(i = 0; i<=n; i++)

There are two things has to be considered in this program.
1 . n = count-1;
for(i = 0; i<n; i++)
The count variable contains the number of element in the array, while n has been assigned to count - 1 to access from the 0th position , but while iterating the loop condition `i<n` make the loop to run n-1 time (i.e 9 times in this case).
So that the sum calculation failed to calculate the last array element.
average = sum/a;
The variable average and sum are float , whereas n is an int, so the type conversion has to be made while calculating the average.
average = sum/(float)a;
NOTE : a should be replaced by count , which hold the exact count of the element in array.
The complete corrected code is,
#include <stdio.h>
int main(void)
{
float numbers[10];
int i;
int n;
int count =0;
for(i = 0; i<10; i++)
{
scanf("%f", &numbers[i]);
count++;
if(numbers[i] == -1)
break;
if(numbers[i] == 0)
break;
}
n = count-1;
float sum = 0;
float average;
for(i = 0; i<=n; i++)
{
sum = sum + numbers[i];
}
average = sum/(float)count;
printf("The average price of the %d products is %.2f.\n", count, average);
return 0;
}

Related

Solving using function in c

Problem is:Write a function that returns the average value of the elements in the array.
This is a solved problem, however I need to solve it via function, and not sure how to do it..Can anyone help please?
#include <stdio.h>
#include <stdlib.h>
int main()
{
int arr[20], num, i; //array declaration
double avg = 0, sum = 0; //variable declaration
printf("Enter the numbers of average: ");
scanf("%d", &num); //get inpur from user to numberof elements
printf("Enter the numbers: \n");
for (i = 1; i <= num; i++)
{ //loop for get input numbers
scanf("%d", &arr[i]);
}
for (i = 1; i <= num; i++)
{
sum = sum + arr[i]; //loop for calculating sum
avg = sum / num; //calculate average
}
printf("Average of entered numbers are: %f", avg);
getch(); //display result on the screen
return 0;
}
A function like this should help:
double calc_average(const int *array, size_t num_elements)
{
double sum = 0.0;
size_t i;
for(i = 0; i < num_elements; i++)
{
sum += array[i];
}
return (sum / num_elements);
}
with this prototype:
double calc_average(const int *array, size_t num_elements);
which you can call with:
avg = calc_average(arr, num);
but you'll need to fix your input loop in main() to start at 0:
for (i = 0; i < num; i++)
and also in main() you should make sure you don't overrun the bounds of your array:
if(num > 20)
{
fprintf(stderr, "Error: too many numbers\n");
return 1;
}
This is simple code. Hopefully, I didn't make any simple mistakes.

Frequency of an Element Accruing In an Array

I am new to programming, I am trying to write a program that lets the user input numbers ranging from 0 to 1000, and the maximum number the user can input is 100. The numbers in the array don't have to be in order, and the program ends when the user inputs a negative number. After that, the program should determine which number occurs the most and the frequency of that occurrence.
I have written a similar code but not for this type of problem the code below showcases what I mean by similar code and any help would be appreciated
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
char again;
do {
srand(time(0));
int myNumbers[10];
int i, n, findnum, time, num;
n = 10;
for (i = 0; i < n; i++) {
myNumbers[i] = rand() % 10 + 1;
}
for (i = 0; i < n; i++) {
printf("elements %d\n", myNumbers[i]);
}
printf("Enter number to find Occurrence: ");
scanf("%d", &findnum);
time = 0;
for (i = 0; i < n; i++) {
if (myNumbers[i]==findnum)
time++;
}
if (findnum>0) {
printf("Occurrence of %d is: %d times\n",findnum,time);
} else {
printf("The number %d is not present in the array\n",num);
}
do {
printf("Shall we play again (y/n)?: ");
while(getchar()!='\n');
scanf("%c", &again);
}
while(again !='y' && again !='n');
}
while(again =='y');
}
You will need a second array to count the frequencies. Worst case, the user entered unique numbers, so the second array should be as large as myNumbers. The array will hold two values: the number, and its count:
int myNumbers[10];
int myCount [10][2] = {0};
int n= 10;
You remember the first entry of myCount that is available:
int m= 0;
You cycle over all numbers:
for (i = 0; i < n; i++){
For each number, you check if it is already in the myCount and if yes, increment the count and then exit the loop:
for (j = 0; j < m; j++){
if (myCount[j][0] == myNumbers[i]){
myCount[j][1]++;
break;
}
}
If the number was not found, you add it:
if (j == m) {
myCount[m][0] = myNumbers[i];
myCount[m][1] = 1;
m++;
}
}
Now you can search the array for the number with the highest count.
Integrated the code is:
int myNumbers[10];
int myCount [10][2] = {0};
int n= 10;
int m= 0;
/* now fist read the input */
for (i = 0; i < n; i++){
for (j = 0; j < m; j++){
if (myCount[j][0] == myNumbers[i]){
myCount[j][1]++;
break;
}
}
if (j == m) {
myCount[m][0] = myNumbers[i];
myCount[m][1] = 1;
m++;
}
}
To do: search the array for the number with the highest count.

sum elements of matrix and calculate the average of the i-th line

Hi all i have a problem with this exercise in Language C.
The exercise is:
Given a matrix write a function that:
A) Calculate and return the sum of the elements.
B) Calculate and return the average of the i-th line
I did my own procedure but i have a lot errors.
My procedure is:
#include <stdio.h>
#include <stdlib.h>
void main(){
int n=10;
int m=10;
int i;
int j;
int mat [i][j];
int sum=0;
for (i=0;i<n;i++){
for (j=0; j<m;j++)
sum=sum+mat[i][j];}
printf("The sum of all elements of matrix is:%d",sum);
somma=0;
for (j=0;j<m;i++){
sum=sum+mat[i][j];
sum=sum/m
printf("The average of i-th line is:%d",sum);
}
}
i think that i have to put scanf somewhere but i don't know where.
I hope that you can help me
thank you!
You declare a matrix with undefined sizes
int mat [i][j];
where i and j are uninitizlized.
You probably want
int mat [n][m];
Moreover your matrix should be inizialized with values, otherwise you'll get the sum of stack garbage.
At the end, a possible solution is
#include <stdio.h>
int main(void)
{
int n = 2;
int m = 2;
int i;
int j;
int mat[n][m];
int sum = 0;
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
{
printf("Insert value of mat[%d][%d]: ", i, j);
scanf("%d", &mat[i][j]);
}
}
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
{
sum = sum + mat[i][j];
}
}
printf("The sum of all elements of matrix is: %d\n", sum);
for (i = 0; i < n; i++)
{
sum = 0;
for (j = 0; j < m; j++)
{
sum = sum + mat[i][j];
}
sum = sum / m;
printf("The average of line %d is: %d\n", i, sum);
}
}
As you can see I changed the average calculation:
First of all you wrote a j loop incrementing i
You must loop for all lines, so you must add a for loop that inc rows
sum must be reset each time you calculate the row average
take notes that the average is calculated using integers, so no decimals will be available.

Most of the program works, but my array isn't printing the way it should

My array isn't printing out all the data, just whatever was last inputted. The data should print something like this
For the student number, if not enough numbers are inputted, 0's are automaticaly put in.
/*
Name:
Date: 10/06/2016
Workshop 4
*/
#include <stdio.h>
int main(void)
{
int counter;
int marks [40];
float num_grades = 0;
int row = 1;
float sum = 0;
float average = 0;
int pass = 0;
int fail = 0;
float pass_sum = 0;
float fail_sum = 0;
float pass_average = 0;
float fail_average = 0;
float biggest = 0;
float smallest = 0;
//int grade[40];
int student_num[40];
printf(" ---=== IPC mark Analyser V2.0 ===---\n");
printf("Please enter the number of students(between 3 and 40): ");
scanf("%d", &counter);
while (counter >40 || counter <3)
{
printf("Invalid number, enter a number between 3 and 40 inclusive: ");
scanf("%d", &counter);
}
printf("Row Std No Mrk\n");
printf("--- --------- ---\n");
num_grades = counter;
while (counter > 0)
{
printf("%d ", row);
printf("_____________ ___\r%3d ", row);
scanf("%d", &student_num[40]);
scanf("%d", &marks[40]);
row++;
counter--;
sum += marks[40];
}
for (int i = 0; i < num_grades; i++)
{
printf("%03d %09d %3d\n", row, student_num[40], marks[40]);
}
average = sum / num_grades;
printf("-----------------\n");
printf("-----------------\n");
printf("Marks Entered, printing results:\n");
printf("Row Std No Mrk\n");
printf("--- --------- ---\n");
printf("The average of all marks in this group is %.1f.\n", average);
printf("Program Ended.\n");
return 0;
}
You're always reading/writing index 40 in the student_num and marks arrays, so everything goes to the same place.
Actually, the valid indexes of an array of size 40 are 0 to 39, so you're actually reading/writing off the end of the array, causing undefined behavior.
You need to use the proper index in each place. In the printing loop, use i. In the reading loop, use a variable that starts at 0 goes up to counter.
num_grades = counter;
for (int i = 0; i < num_grades; i++)
{
printf("%d ", i + 1);
printf("_____________ ___\r%3d ", i + 1);
scanf("%d", &student_num[i]);
scanf("%d", &marks[i]);
sum += marks[i];
}
for (int i = 0; i < num_grades; i++)
{
printf("%03d %09d %3d\n", row, student_num[i], marks[i]);
}

Finding Max value and Average Of All elemements in 2D array in C

EDIT II
I'm finally getting somewhere, now i get my random values with a return from the maxavg() function.
My only question now is, when i run the program i always get:
average: 0
maximum: 33
why? it does not make much sense.
Here is the new code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <limits.h>
int GetRand(int min, int max);
struct maxavg;
int main ()
{
int a[21][21], i , j, average, maximum, ret;
for (i = 0; i < 21; i++)
{
for ( j = 0; j < 21; j++)
{
a[i][j] = GetRand(0, 100);
printf("%3d" , a[i][j]);
}
a[2][15] = -1;
a[10][6] = -1;
a[13][5] = -1;
a[15][17] = -1;
a[17][17] = -1;
a[19][6] = -1;
printf("\n");
}
printf("average = %d \n maximum = %d", average, maximum);
return 0;
}
// random seed
int GetRand(int min, int max);
int get ()
{
int i, r;
for (i = 0; i < 21; i++)
{
r = GetRand(0, 100);
printf("Your number is %d \n", r);
}
return(0);
}
int GetRand(int min, int max)
{
static int Init = 0;
int rc;
if (Init == 0)
{
srand(time(NULL));
Init = 1;
}
rc = (rand() % (max - min +1) +min);
return (rc);
}
struct pair
{
int max;
int avg;
};
// max and average
struct pair maxavg()
{
struct pair p;
int max=INT_MIN, sum=0, count=0, avg, i, j, current;
for(i = 0; i < 21; i++){
for(j =0; j < 21; j++){
if(current > -1){
sum = sum + current;
count = count + 1
;if(current > max){
max = current;
}
}
}
}
avg = sum/count;
printf("Max is %d \n", max);
printf("Average is %d \n", avg);
p.max = max;
p.avg = avg;
return p;
}
EDIT:
So here is what i'm doing, i get error messages:
Average:
// Average Code
value = a[i][j];
int actualvalue, suma = 0, quant;
for(i=0; i<21; i++){
for(j=0; j<21; j++){
if (actualvalue > -1){
a[i][j] = actualvalue;
suma = suma + actualvalue;
// sum actual value + nextvalue (sum of all > -1) //
}
else if {
quant = quant + 1;
//(sum the quantity of times a value has been greater than -1)//
}
}
}
printf("The average value is:", suma/quant); ///(sun of all values > -1)/(sum of quantity value was > -1)/
Find Maximum:
// Max
int variableP = a[0][0];
value = a[i][j];
int variableP = a[i][j]
for(i=0; i<21; i++){
for(j=0; j<21; j++){
if(variableP < newvalue){
variableP = newvalue
}
}
}
printf("The max value of the 2D array is", %d);
Average and Maximum:
// max and average
int maxvg();
int max=INT_MIN, sum=0, count=0, avg;
for(i = 0; i < 21; i++){
for(j =0; j < 21; j++){
if(current > -1){
sum = sum + current;
count = count + 1
if(current > max){
max = current;
}
}
}
}
avg = sum/count;
printf("Max is %d \n", max);
printf("Average is %d \n", avg);
So how right or wrong is this? what am i missing.
i mostly get:
[Error] expected '=', ',', ';', 'asm' or '__attribute__' before '<' token
[Warning] data definition has no type or storage class
[Error] initializer element is not constant
[Error] expected declaration specifiers or '...' before string constant
Am i at least close to it?
Thanks in advance.
END OF EDIT
I created a 2D array with random numbers from 0 to 100 (and a couple of -1) values with this code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
int a[21][21], i, j;
for (i = 0; i < 21; i++) {
for (j = 0; j < 21; j++) {
a[i][j] = GetRand (0, 100);
a[7][15] = -1;
a[10][6] = -1;
a[13][5] = -1;
a[15][17] = -1;
a[17][17] = -1;
a[19][6] = -1;
printf ("%3d", a[i][j]);
}
printf ("\n");
}
return 0;
}
// random seed
int GetRand (int min, int max);
int get ()
{
int i, r;
for (i = 0; i < 21; i++) {
r = GetRand (0, 100);
printf ("Your number is %d \n", r);
}
return (0);
}
int GetRand (int min, int max)
{
static int Init = 0;
int rc;
if (Init == 0) {
srand (time (NULL));
Init = 1;
}
rc = (rand () % (max - min + 1) + min);
return (rc);
}
This prints the array created. Now I want to calculate the maximum value of all values inside the array and the total average of all values in the array, all while ignoring all -1 values, so only from 0 to 100. Since I'm a total beginner I'm having problems creating these functions. So here are my ideas.
//For the average
for(i=0; i<1; i++){
for(j=0; j<21; j++){
if (actualvalue > -1){
//sum actualvalue + nextvalue (sum of all the values greater than -1)//
}
else if (actualvalue > -1){
//(sum the quantity of times a value has been greater than -1)//
}
}
}
}
printf("The average value is", //(sum of all values>-1)/(sum of quantity value was >-1) //);
I'm representing the thing i don't know how to write in code in words so you get my idea.
Now for finding the maximum: what i think i should do is initialize the array and make a variable adopt the first value it finds that's > -1, then rewind and initialize again, if the actualvalue < newvalue then make variableP adopt the newvalue:
//max
int variableP = a[i][j]
for(i=0; i<21; i++){
for(j=0;j<21;j++){
if(variableP < newvalue){
variableP = newvalue
}
printf("The max value of the 2D array is", %d);
}
I know it's evident i'm not sure what i'm writing here, but i think my idea of it is correct, i hope i'm explaining it well enough.
Sum is as you say.
Average requires you count number of >-1 values.
Max looks right lines. Finish off your ideas and ask again if it doesn't work
You can do both max and avg in one loop.
Declare three variables: max=-999999, sum=0, count=0.
Each time when current cell is not -1 increase sum by it's value and count by 1.
Each time check if current value is bigger than max, then set max to current value.
After the loop is done, avg = sum/count.
Consider you are doing all your arithmetic using integers, and integer division is integer. Perhaps you have better to do a double result with:
/* you don't actually need to cast to double in both operators, as the
* one not casted will be automagically casted to double to operate on.
*/
double average = (double) sum_of_samples / (double) number_of_samples;
You have to cast at least one of the operators, because if you don't you'll get the result as before (a 0 integer result) converted to double to assign to the variable.

Resources