Why won't the average column amount not calculate? - arrays

I want to print out the average amount of an 2D array column, by filling the matrix with random numbers
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int m = 0;
int n = 0;
int array[m][n];
double ran_num = (double)rand() / RAND_MAX;
double avg_col[] = {0};
printf("Enter (m, n > 0): ");
scanf("%d, %d", &m, &n);
for(size_t i = 0; i <= m; ++i){
for(size_t j = 0; j <= n; ++j){
array[i][j] = ran_num;
avg_col[j] += array[i][j] / m;
}
}
for(int i = 0; i < n; i++){
printf("Average of column %d : %.3f\n", i ,avg_col[i]);
}
return 0;
}
But the output is:
Average of column 0 : 0.000
Average of column 1 : 0.000
Average of column 2 : 0.000
I can't figure out where the problem is.
Maybe you can help me, I would really appreciate it.

In this line:
avg_col[j] += array[i][j] / m;
variable array[i][j] is an integer, and variable m is an integer.
So you are doing integer division. If the denominator m is greater than the numerator array[i][j], then the result is ZERO.
Example:
5 / 10; // Humans think the result is 0.5. Programmers know the result is 0.

Fixed up for you.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int m = 0;
int n = 0;
printf("Enter (m, n > 0): ");
scanf("%d, %d", &m, &n);
double array[m][n];
double avg_col[n];
memset(avg_col, 0, sizeof(avg_col));
for(size_t i = 0; i < m; ++i){
for(size_t j = 0; j < n; ++j){
array[i][j] = ((double)rand()) / RAND_MAX;
avg_col[j] += (double)array[i][j] / m;
}
}
for(int i = 0; i < n; i++){
printf("Average of column %d : %.3f\n", i ,avg_col[i]);
}
return 0;
}
Output (with input 5, 10)
Success #stdin #stdout 0s 5460KB
Enter (m, n > 0): 5, 10
Average of column 0 : 0.475
Average of column 1 : 0.575
Average of column 2 : 0.460
Average of column 3 : 0.661
Average of column 4 : 0.588
Average of column 5 : 0.478
Average of column 6 : 0.480
Average of column 7 : 0.697
Average of column 8 : 0.356
Average of column 9 : 0.620

Related

I get different outputs when i use different compilers

I was trying to solve a problem with using C. But I got different outputs in different compilers. First I tried gcc and there was no mistake but when I use clang the output changed.
PROBLEM:
Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.
Sample Input: 1 2 3 4 5
Sample Output: 10 14
10 = 1 + 2 + 3 + 4 | 14 = 2 + 3 + + 4 + 5
The Output when I use clang: 1 14
Here is the code:
#include <stdio.h>
void miniMaxSum(int *a, int b) {
int sums[5] = { b, b, b, b, b };
int min = *a, max = *a;
for (int j = 0; j < 5; j++) {
sums[j] -= *(a + j);
if (sums[j] < min)
min = sums[j];
if (toplamlar[j] > max)
max = sums[j];
}
printf("%d %d\n", min, max);
}
int main() {
int numbers[5] = { 0, 0, 0, 0, 0 };
int sum;
for (int i = 0; i < 5; i++) {
scanf("%d ", &numbers[i]);
toplam += numbers[i];
}
miniMaxSum(numbers, sum);
return 0;
}
EDIT: Sorry, I changed the variables name to English sake of understanding, but I forgot the toplam (sum) and toplamlar (sums).
Assuming you translated some of the variable names to English for non Turkish speakers, the variable sum (toplam) is uninitialized leading to undefined behavor. A common symptom for undefined behavior is different behavior on a different system / compiler.
Note that you can simplify your code by just searching for the minimum and maximum values in the array:
#include <stdio.h>
void miniMaxSum(const int *a, int sum) {
int min = a[0], max = a[0];
for (int j = 1; j < 5; j++) {
if (sums[j] < min)
min = sums[j];
if (sums[j] > max)
max = sums[j];
}
printf("%d %d\n", sum - max, sum - min);
}
int main() {
int numbers[5] = { 0, 0, 0, 0, 0 };
int sum = 0;
for (int i = 0; i < 5; i++) {
scanf("%d ", &numbers[i]);
sum += numbers[i];
}
miniMaxSum(numbers, sum);
return 0;
}

multiplying number from 1 to N while adding 2 every time

I have to write a C program that multiplies numbers from 1 to N.
N is scanned. Before multiplication, I have to increase each number by 2.
For example: N = 3 => (1+2)(2+2)(3+2) = 60
I have to only use while loop and print and scan function.
Example program:
Enter the value of N: 4
The result of multiplication: 360
This is my code and I am not sure what is wrong with this. Please help.
#include <stdio.h>
int N;
int count=1, ii, result;
printf("Enter the value of N:");
scanf("%d", &N);
while (count<=N)
{
count ii = count + 2;
ii = ii * ii ; //three
count++;
}
result = ii;
printf("The result of multiplication: %d", result);
return 0;
}
If you're looking for that series as a sum:
const int N = 3;
int c = 1;
for (int i = 1; i <= N; ++i) {
c *= (i + 2);
}
Or in a more C-esque form:
const int N = 3;
int c = 1;
for (int i = 0; i < N; ++i) {
c *= (i + 1 + 2);
}
int main()
{
int N;
int count=1, ii = 1, result;
printf("Enter the value of N:");
scanf("%d", &N);
while (count<=N)
{
ii = ii * ( count + 2 };
count++;
}
result = ii;
printf("The result of multiplication: %d", result);
return 0;
}

Error converting a integer value to float in c

What I have so far...
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROWS 23
#define COLS 78
int main()
{
srand(time(NULL));
int arr[ROWS][COLS];
int sum = 0, counter1 = 0;
int k;
int i;
for (i = 0; i < ROWS; i++)
{
for (k = 0; k < COLS; k++)
{
int j = rand() % 10;
arr[i][k] = j;
printf("%d", arr[i][k]);
sum += arr[i][k];
counter1++;
}
printf("\n");
}
printf("\n");
printf("Average = %f\n", float(sum / counter1)); //Not getting exact decimal
printf("Total numbers = %d\n", counter1);
printf("Sum of all numbers = %d\n", sum);
system("pause");
}
//Guessing the float is not converting as it should
Output so far....
422620351595919054460397694388416319310552973446498175458548095262118564755749
372438759420195802623062987655437952542263796363224469905714526364539742622586
124057899145417666187341286327350448786294141128615529044980269471365598313616
049149926286317172502475330649055931769733144700851693923585818341846097713250
826490802265735183843662244505193942554706854717207204487697516652123593599812
746605634674496934691593122520210519087830081107377133858638184877543092242563
172193699659454833537193985400677695430588428833192355923118027599256651906912
137220359907772463940456613321876957716810615732837946886780325557272201117024
970243922687865367166306388461501128523059854106020838236007732376011146109340
239699228705450117510917862089719947717228921040726908237444581851160698373585
977683407031265082736130690889715335368791599705700863736964292214408266990418
536416318005520152773513475211623892873091447652802755401011207564392549940648
363921632561931849591970346553864295588487844510186065223062209484132581237554
163065518327032754274153946192470922485557045255627009864269391575284952286729
910378772792028085274954077343530447604501744264499511471498074681140863439500
617676961625579079414287810415495010710519733811672377499905168756599387590803
885768234776892368128405809649999684460473809170548180074483476110165080161362
308905170626655925452893089531708914818032726022522429229062646282887593747734
210270837200571461718554091036728525587376768397741678405601722794577171279012
421649999013761899858408492974830996084297030747093760611147983343593657910519
461743953198670501367758536958306703445033922711724727706025545309033925365602
635580784707723652610577238350330553362131582484629421787969994692199573628406
521293251392156351047950677006976709658442231650692040031419198232429972214834
Average = 4.000000
Total numbers = 1794
Sum of all numbers = 8054
Press any key to continue . . .
You can format the number to 2 decimal place by placing ".2f" :
printf("Average = %.2f\n", float(sum) / float(counter1));
float(sum / counter1) --> (float)sum / counter1
– BLUEPIXY

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

How to find the biggest sum of a given scope in a 2D array?

I need to know how to find the biggest sum of a given scope in a 2D array, preferably in C to improve the efficiency of the code give below and solve the problem.
To understand this better, read the problem I need to solve below.
Problem
The great city X is a grid of N rows and M columns. There are given
number of people living in each cell. You are asked to position the
telecommunication tower so that as many as people are satisfied. The
cellular tower can cover a rectangular area of Y rows and X columns.
Find the maximum number of people you can satisfy.
Constrains
1 <= N, M <= 1000
1 <= Y <= N, 1 <= X <= M
1 <= number of people in a cell <= 1000
Rectangular area covered by the celluar tower should not cover any cell partially.
Input
First line of the input will contain 4 digits N, M, Y and X respectively separated by spaces. Each of next N lines with contains integers of row 1 to N. Each row will M integers giving the number of people living in each cell separated by spaces.
Output
Output should contain only one integer, the maximum number of people you can satisfy.
Sample Input
4 5 2 3
3 1 1 1 2
2 5 6 7 1
1 2 9 9 1
1 1 1 1 1
Sample Output
38
Explanation
Maximum number of people can be satisfied by placing the tower covering 2x3 area that consists of 5, 6, 7, 2, 9 and 9 cells.
5 + 6 + 7 + 2 + 9 + 9 = 38
My code
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int N, M, Y, X;
scanf("%d %d %d %d", &N, &M, &Y, &X);
int max = 0;
int total = 0;
int data[N][M];
for(int i = 0; i < N; i++)
for(int j = 0; j < M; j++)
scanf("%d",&(data[i][j]));
for(int i = 0; i < N; i++)
{
for(int j = 0; j < M; j++)
{
total = 0;
for(int l = 0; (l < Y) && (i + Y) <= N; l++)
{
for(int k = 0; (k < X) && (j + X <= M); k++)
{
total += data[i+l][j+k];
}
if(total > max)
max = total;
}
}
}
printf("%d",max);
return 0;
}
This code fails because it's too linear and takes a lot of time when a larger input is used.
You can try out the problem yourself, here
I suppose the main problem in your solution of Number Grid problem is nested for loops. The simplest optimization is to minimaze number of recalculations for each move of the scope.
I tryed the following changes in the original code:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int N, M, Y, X;
scanf("%d %d %d %d", &N, &M, &Y, &X);
int max = 0;
int total = 0;
int data[N][M];
for(int i = 0; i < N; i++)
for(int j = 0; j < M; j++)
scanf("%d",&(data[i][j]));
////////////////////////////////////////////////////////////
// calculation of the first total and initial max
int startTotal = 0;
int r, c;
for(r = 0; r < Y-1; r++)
{
for(c = 0; c < X-1; c++)
{
startTotal += data[r][c];
}
}
max = startTotal;
for(int i = 0; i+Y <= N; i++)
{
// add next line
for(int c = 0; c < X-1; c++)
{
startTotal += data[i+Y-1][c];
}
total = startTotal;
for(int j = 0; j+X <= M; j++)
{
// add next column
for(int r = i; r < i+Y; r++)
total += data[r][j+X-1];
// compare
if(total > max)
{
max = total;
}
// subtract the first column
for(int r = i; r < i+Y; r++)
total -= data[r][j];
}
// subtract the first line
for(int c = 0; c < X-1; c++)
{
startTotal -= data[i][c];
}
}
////////////////////////////////////////////////////////
printf("%d",max);
return 0;
}
I have tryed to run the program at hackerrank.com, and received

Resources