How can I find the element closest to average in c array. This passes most tests however when I type in the sequence 4-1-5-7-2 it prints out 2, instead of 5.
#include <stdio.h>
#include <math.h>
int main() {
int A[50], n, k = 0, i = 0;
double avg = 0;
scanf_s("%d", &n);
do {
scanf_s("%d", &A[i]);
avg += (double)A[i] / n;
} while (++i < n);
printf("\n%f\n", avg);
for (i = 1; i < n; i++) {
if (fabs(A[k] - avg) > fabs(A[i]) - avg) {
k = i;
}
}
printf("%d", A[k]);
return 0;
}
In your if statement, replace fabs(A[i]) - avg with fabs(A[i] - avg) to get the absolute difference.
Related
I want to write a program where a user tells me an integer(n) and i calculate The sum of 1+(1-2)+(1-2+3)+(1-2+3-n)... where even integers are -k and odd integers are +k.
Ive made a function which does that But the sum is never correct. For example for n=2 it should be sum=0 but shows sum=-1 for n=3 should be sum=+2 but i shows sum=3. (Ignore the debugging printfs)
#include <stdio.h>
int athroismaAkolouthias(int n); // i sinartisi me tin opoia ypologizete to athroisma akolouthias 1+(1-2)+(1-2+3)+(1-2+3-4).....
int main(){
int n;
printf("give n: ");
scanf("%d", &n);
printf("the sum is %d", athroismaAkolouthias(n));
}
int athroismaAkolouthias(int n){
int sum1=0, sum2=0,sum=0;
int i, temp, j;
for (i=1; i<=n; i++){
for (j=1; j<=i; j++){
temp=j;
}
if (i%2==0){sum=sum-temp; printf("test1 %d%d",sum,temp);}
else{sum=temp; printf("test2 %d%d",sum,temp);}
}
return sum;
}
Your issue is with our loop which iterate with j, it should update the inner_sum based on j even/odd condition as follows:
#include <stdio.h>
int akl(int n) {
int sum = 0;
for (int i = 1; i <= n; i++) {
int inner_sum = 0;
for (int j = 1; j <= i; j++) {
if (j % 2 == 0) {
inner_sum -= j;
} else {
inner_sum += j;
}
}
sum += inner_sum;
}
return sum;
}
int main() {
int n;
scanf("%d", &n);
printf("%d\n", akl(n));
}
You only need two variables for sum that I named them inner_sum and sum which shows the sum of each term and sum over all terms.
Suspicious Line: else {sum = temp; ...
Shouldn't you be adding or subtracting to sum every time??
Why are you assigning to it here, without an addition or subtraction?
You also have variables sum, sum1, and sum2.
You print sum1 and sum2, but never modify them.
Here's my solution:
// The sum of 1+(1-2)+(1-2+3)+(1-2+3-n)... where even integers are -k and odd integers are +k.
#include <stdio.h>
int ancho(int n)
{
int sum=0;
for(int i=1; i<=n; ++i)
{
for(int j=1; j<=i; ++j)
{
sum += (2*(j%2)-1)*j;
}
}
return sum;
}
int main(void)
{
int n = 5;
printf("Solution is %d\n", ancho(n));
}
// Solution is 3 for n = 5,
// because: 1 + (1-2) + (1-2+3) + (1-2+3-4) + (1-2+3-4+5) =
// 1-1+2-2+3 = 3
Output
Success #stdin #stdout 0s 5476KB
Solution is 3
IDEOne Link
#include <stdio.h>
int sum_even(int n);
int sum_odd(int m);
int main() {
int n;
scanf("%d", &n);
int m;
scanf("%d", &m);
int evensum;
evensum = sum_even(int n);
int oddsum;
oddsum = sum_odd(int m);
printf("the sum of even numbers is %d", evensum);
printf("the sum of odd numbers is %d", oddsum);
return 0;
}
int sum_even(int n) {
int sum = 0, i;
for (i = 2; i <= n; i += 2) {
sum += i;
}
return sum;
}
int sum_odd(int m) {
int SUM = 0, j;
for (j = 1; j <= m; j = j + 2) {
SUM = SUM + j;
}
return SUM;
}
please tell me what is wrong with my code, I am new to coding, I am able to solve questions without using functions but I am confused when I have to use functions
While calling functions you just pass the arguments and not specify its data type.
i.e. You would write it like this :-
evensum = sum_even(n);
oddsum = sum_odd(m);
The general syntax of calling a function which returns a value is :-
return-value = function-name(arg-list);
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.
I need a program to evaluate Min, Max, Avg and Geometric avg of any number of integers. This is what I've come up with so far. Min and Max were working just fine until I added the Avg. Now Min and Avg is working right but Max gives wrong number (usually the second greatest number). Also geometric avg gives only 0.00000. Thanks for your help.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char const *argv[]) {
int arr[100], max, i, min, size, lok = 1;
float arit = 0, geom = 0, sum = 0, prod = 0;
printf("\nSay how many integers you want to input: ");
scanf("%d", &size);
printf("\nType %d integers: ", size);
for (i = 0; i < size; i++) //put values in arr
scanf("%d", &arr[i]);
max = arr[0];
min = arr[0];
for (i = 1; i < size; i++) { //calc maximum
if (arr[i]>max) {
max = arr[i];
lok = i+1;
}
if (arr[i]<min) { //calc minimum
min = arr[i];
lok = i+1;
}
for (i = 0; i < size; i++) { //calc avg
sum = sum + arr[i];
}
arit = sum/size;
for (i = 0; i < size; i++) {
prod = prod * arr[i];
}
geom = pow(prod, 1./size);
}
printf("\n%d is maximum", max);
printf("\n%d is minimum", min);
printf("\n%f is avg", arit);
printf("\n%f is geometric avg", geom);
return 0;
}
The two main problems were
a misplaced closing } brace
wrong intialisation of prod = 0
I have made some other changes too:
check the validity of the inputs
use double instead of float (unless a good reason not to).
remove the unused lok
only one loop is needed for all the statistics
moved the position of the \n newlines as is customary.
This is the amended code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char const *argv[]) {
int arr[100], max, i, min, size;
double arit = 0, geom = 0, sum = 0, prod = 1; // init prod to 1
printf("\nSay how many integers you want to input: ");
if(scanf("%d", &size) != 1 || size < 1 || size > 100) {
exit(1); // or other action
}
printf("\nType %d integers:\n", size); // added newline
for (i = 0; i < size; i++) {
if(scanf("%d", &arr[i]) != 1) {
exit(1); // or other action
}
}
max = arr[0];
min = arr[0];
for (i = 0; i < size; i++) { // just one loop
if (arr[i] > max) {
max = arr[i];
}
if (arr[i] < min) {
min = arr[i];
}
sum = sum + arr[i];
prod = prod * arr[i];
}
arit = sum / size;
geom = pow(prod, 1.0 / size);
printf("%d is maximum\n", max); // reposition newlines
printf("%d is minimum\n", min);
printf("%f is avg\n", arit);
printf("%f is geometric avg\n", geom);
return 0;
}
This will fix your problem with Min and Max, and I guess also will fix geometric mean(check it) It was a problem closing for sentences
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char const *argv[]) {
int arr[100], max, i, min, size, lok = 1;
float arit = 0, geom = 0, sum = 0, prod = 1;
printf("\nSay how many integers you want to input: ");
scanf("%d", &size);
printf("\nType %d integers: ", size);
for (i = 0; i < size; i++) //put values in arr
scanf("%d", &arr[i]);
max = arr[0];
min = arr[0];
for (i = 1; i < size; i++) { //calc maximum
if (arr[i]>max) {
max = arr[i];
lok = i+1;
}
if (arr[i]<min) { //calc minimum
min = arr[i];
lok = i+1;
}
}
for (i = 0; i < size; i++) { //calc avg
sum = sum + arr[i];
}
arit = sum/size;
for (i = 0; i < size; i++) {
prod = prod * arr[i];
}
geom = pow(prod, 1./size);
printf("\n%d is maximum", max);
printf("\n%d is minimum", min);
printf("\n%f is avg", arit);
printf("\n%f is geometric avg", geom);
return 0;
}
About Geometric mean you are doing this.
float arit = 0, geom = 0, sum = 0, prod = 0;
and then
for (i = 0; i < size; i++) {
prod = prod * arr[i];
}
That allways will return 0 because you initialize prod at 0
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.