How to know which row has the greatest sum - c

I am writing this program to find the sum of each row, and find the row with the highest sum. however, the sums of each row execute perfectly, but I can't be shown the highest sum.
#include<stdio.h>
int main()
{
int type[5][3]={{3,31,19},{34,2,1},{0,0,9},{3,0,6},{11,9,5}};
for(i=0;i<5;++i)
{
for(j=0;j<3;++j)
{
sum=sum+type[i][j];
if((sum=sum+type[i][j])>(sum=sum+type[i+1][j]))
{
printf("%d type is highest",i);
}
}
printf("Total sumt %d=%d\n",i+1,sum);
sum=0;
}
}

Your program has the following errors:
if((sum=sum+type[i][j])>(sum=sum+type[i+1][j])) will go out-of-bound of array.
The highest value must be printed outside of all the loops and assigned during loop execution.
There you go with correct program:
#include <stdio.h>
int main(void) {
int arr[][3] = {{3, 31, 19}, {34, 2, 1}, {0, 0, 9}, {3, 0, 6}, {11, 9, 5}};
size_t len = sizeof(arr) / sizeof(arr[0]);
int sum = 0, largest = 0, index = 0;
for (int i = 0; i < len; i++) {
for (int j = 0; j < 3; j++) {
sum += arr[i][j];
if (sum > largest) {
largest = sum; // getting the largest number
index = i; // getting the index of the largest number
}
}
printf("The sum of %d is: %d\n", i + 1, sum);
sum = 0;
}
printf("Highest: %d with %d\n", largest, index);
return 0;
}
This will print the highest number alongside the index where the highest number is provided.
You'll then get something like:
The sum of 1 is: 53
The sum of 2 is: 37
The sum of 3 is: 9
The sum of 4 is: 9
The sum of 5 is: 25
Highest: 53 with 0 // 0 is the index of the array, not counting as a number

Store sum of all the 5 rows of int type[5][3] in any array, say sum[5] and then find the highest of them and then print their index+1 no. to show that, this row has the highest sum.
Example:
#include <stdio.h>
#define ROW 2
#define COLUMN 3
int main(void)
{
int type[ROW][COLUMN] = { {1, 2, 3}, {4, 5, 6}};
int sum[ROW] = {0, 0};
int i, j, row = 0, highest = 0;
for ( i = 0; i < ROW; ++i)
for ( j = 0; j < COLUMN; ++j)
sum[i] += type[i][j];
for ( i = 0; i < ROW; ++i)
if(highest < sum[i])
{
highest = sum[i];
row = i;
}
printf("Row %d has the highest sum value %d.\n", row, highest);
return 0;
}

You have a number of problems. i and j are not declared, and you read beyond the end of type with type[i+1][j]. You must fix both.
To find the largest sum, you need a separate variable that holds the largest of the sums seen and then after you exit your last loop, then output the biggest sum, e.g.
(updated to include row where largest sum occurs)
#include <stdio.h>
#include <limits.h>
int main (void) {
int type[5][3] = {{3,31,19}, {34,2,1}, {0,0,9}, {3,0,6}, {11,9,5}},
biggest = INT_MIN, /* variable to hold biggest sum */
bigindex = 0; /* variable to hold row of biggest */
for (int i = 0; i < 5; i++) { /* loop over each row */
int sum = 0; /* declare/initialize sum = 0 */
for (int j = 0; j < 3; j++) { /* loop over each int */
sum += type[i][j]; /* add int to sum */
}
if (sum > biggest) { /* compare sum to biggest sum */
biggest = sum; /* update biggest if sum larger */
bigindex = i + 1; /* update row where it occurs */
}
printf ("Total sum type[%d] = %d\n",i+1, sum); /* output sum */
}
/* output largest sum and row where it occurred */
printf ("Largest sum: %d at row %d\n", biggest, bigindex);
}
Example Use/Output
$ ./bin/biggestsum
Total sum type[1] = 53
Total sum type[2] = 37
Total sum type[3] = 9
Total sum type[4] = 9
Total sum type[5] = 25
Largest sum: 53 at row 1
Let me know if you have further questions.

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;
}

Find a set of the most common numbers in a randomly filled array

Good afternoon, and I have one question to ask about programming lottery in C language.
The requirements are:
Calculate each number's chance when if there are 46 balls labeled in each number in the box and there are 10K chances to pick one ball.
Then, print the number and number's chance on each item. The printed form must be like:
Number 45: 251 times
Find six of the most found numbers and print them out. The printed form must be like:
The most found were 45, 27, 8, 10, 12, 15
So my code was:
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10000
#define ballamount 6
int main(void)
{
int fq[SIZE] = {0};
int i, max = 0, maximum1 = 0, temp = 0;
for (int i = 0; i < SIZE i++)
{
++fq[rand() % 45 + 1];
}
for (i = 0; i < 45; i++)
{
printf("number %d: %d times\n", i + 1, fq[i]);
}
for (i = 0; i < ballamount i++)
{
for (int j = 0; j < 45; j++)
{
fq[j] = fq[0];
if (fq[j] > temp)
{
temp = fq[j];
max = j;
}
}
fq[i] = max;
fq[max] = 0;
printf("Maximum number is %d.\n", max);
}
return 0;
}
I cannot find the path to solve this stuff. How can I solve it? Thanks in advance.
You're almost there, fq contains the number of times a given index is randomly selected, you already have that, you just have to select the six largest values in the array, minor tweaks to your code will render you the correct result.
Your code fixed, including ; typos, in the for loops, with comments:
Live demo
#include <stdio.h>
#include <stdlib.h>
#include <time.h> // for the seed
#define SIZE 10000
#define ballamount 6
int main(void)
{
srand(time(NULL)); // add a seed for your random number generator
int fq[46] = {0}; // the array only needs 46 elements
int max = 0;
int temp = 0;
for (int i = 0; i < SIZE; i++) // was missing ;
{
++fq[rand() % 46]; // if it's from 1 to 46, use index 0 to 45
}
for (int i = 0; i < 46; i++) // index 0 to 45
{
printf("number %d: %d times\n", i + 1, fq[i]);
}
printf("The most found balls were: ");
for (int i = 0; i < ballamount; i++) // was missing ;
{
for (int j = 0; j < 46; j++)
{
if (fq[j] > temp)
{
temp = fq[j];
max = j;
}
}
printf("%d ", max + 1); // adding 1, index starts at 0
fq[max] = 0;
temp = 0; // reset temp after the loop
}
}
Possible output:
number 1: 194 times
number 2: 187 times
...
...
The most found balls were: 28 30 43 5 29 12

if sum of 2 numbers in the array are equal to another number (not in the array)

I am trying to write a program that picks up an array of 10-size numbers and another number. The program will check if there are two numbers in the array so that their sum is the same as a number that is not in the array.
If so, the program will print the 2 numbers, if not the program will print no.
This is what I did until now:
#include <stdio.h>
void main()
{
int array[10], number;
for (int i; i < 10; i++)
{
scanf("%d", &array[i]);
}
scanf("%d", &number);
}
I don't know how to continue from there. Can someone help, please?
Thanks :)
This program should fulfill your needs. It doesn't print a pair twice (e.g. arr[1] + arr[2] and arr[2] + arr[1]) and it doesn't accept the same number times two (e.g. arr[3] + arr[3]). I have included some comments in the code that help explain it.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
/* set your own `sum` and `arr` */
int sum = 14;
int arr[] = {1, 4, 6, 3, 2, 8, 5, 7, 3, 9};
/* calculate size of `arr` */
size_t size = sizeof(arr) / sizeof(int);
for (int i = 0; i < size; ++i) {
/* start from `i + 1` */
for (int j = i + 1; j < size; ++j) {
/* check if the sum is right */
if (arr[i] + arr[j] == sum)
printf("%d + %d = %d\n",
arr[i], arr[j], sum);
}
}
return EXIT_SUCCESS;
}
With the above sum and arr the output of the program will be:
6 + 8 = 14
5 + 9 = 14

How to find which row has the biggest sum in 2D array?

I have 2D array, I need to write a function to find which row has the biggest sum, and if there is more than one row with the same sum, I need to print no particular max. This is what I wrote so far:
int find_max_sum(int b[N][N])
{
int row_sum = 0;
int row_max = -1;
int i,j,k;
int counter=0;
for(int i =0;i<N;i++)
{
row_sum = 0;
for (j = 0; j < N; ++j)
{
row_sum += b[i][j] ;
}
if(row_max < row_sum)
{
row_max = row_sum;
}
}
for (i = 0; i < N; i++)
{
for (j= 0;j< N;j++)
{
if(k=row_max);
counter++;
}
}
if (counter>1)
return(printf("No unique max.\n"));
else
return row_max;
}
Now I need help with the counter thing, and if the function is int how can it return prints? Is it possible?
Here's an example.
#include <stdio.h>
#include <stdbool.h>
#define N 2
#define NO_UNIQUE -1
int find_max_sum(int b[][N])
{
int row_sum, i, j;
int row_max = -1;
bool unique = false;
for (i = 0; i < N; ++i) {
row_sum = 0;
for (j = 0; j < N; ++j)
row_sum += b[i][j];
if (row_max < row_sum) {
row_max = row_sum;
unique = true;
} else if (row_max == row_sum)
unique = false;
}
if (unique)
return row_max;
else {
printf("No unique max.\n");
return NO_UNIQUE;
}
}
int main(void)
{
int b[N][N] = {1, 2, 3, 4};
printf("Max sum is %d\n", find_max_sum(b));
return 0;
}
I suggest you to use a third variable (let's call it rowsWithMaxCount) to store the amount of rows with the current max value such that:
if you find a row with a new maximum then rowsWithMaxCount = 1
if you find a row such that row_max == row_sum then ++rowsWithMaxCount
otherwise rowsWithMaxCount is unaffected
This will save you from looping the bidimensional array, which is a waste of code since you can obtain all the information you need with a single traversal of the array.
"returning a printf" doesn't make any sense and it's not possible, if you declare the function to return an int then you must return an int. Consider using a special value to signal the caller that there is no unique maximum value. Eg, assuming values are always positive:
static const int NO_UNIQUE_MAX = -1;
int find_max_sum(int b[N][N]) {
...
if (counter > 1)
return NO_UNIQUE_MAX;
...
}
But this will prevent you from returning the not-unique maximum value. If you need to return both then you could declare a new type, for example
struct MaxRowStatus {
int value;
int count;
};
So that you can precisely return both values from the function.
You may be over-thinking the function, if I understand what you want correctly. If you simply want to return the row index for the row containing a unique max sum, or print no unique max. if the max sum is non-unique, then you only need a single iteration through the array using a single set of nested loops.
You can even pass a pointer as a parameter to the function to make the max sum available back in your calling function (main() here) along with the index of the row in which it occurs. The easiest way to track the uniqueness is to keep a toggle (0, 1) tracking the state of the sum.
An example would be:
int maxrow (int (*a)[NCOL], size_t n, long *msum)
{
long max = 0;
size_t i, j, idx = 0, u = 1;
for (i = 0; i < n; i++) { /* for each row */
long sum = 0;
for (j = 0; j < NCOL; j++) /* compute row sum */
sum += a[i][j];
if (sum == max) u = 0; /* if dup, unique 0 */
if (sum > max) /* if new max, save idx, u = 1 */
max = sum, idx = i, u = 1;
}
if (u) { /* if unique, update msum, return index */
if (msum) *msum = max;
return idx;
}
fprintf (stderr, "no unique max.\n");
return -1; /* return -1 if non-unique */
}
(note: if you don't care about having the max sum available back in the caller, simply pass NULL for the msum parameter)
A short test program could be the following. Simply uncomment the second row to test the behavior of the function for a non-unique max sum:
#include <stdio.h>
#include <stdlib.h>
enum { NCOL = 7 };
int maxrow (int (*a)[NCOL], size_t n, long *msum)
{
long max = 0;
size_t i, j, idx = 0, u = 1;
for (i = 0; i < n; i++) { /* for each row */
long sum = 0;
for (j = 0; j < NCOL; j++) /* compute row sum */
sum += a[i][j];
if (sum == max) u = 0; /* if dup, unique 0 */
if (sum > max) /* if new max, save idx, u = 1 */
max = sum, idx = i, u = 1;
}
if (u) { /* if unique, update msum, return index */
if (msum) *msum = max;
return idx;
}
fprintf (stderr, "no unique max.\n");
return -1; /* return -1 if non-unique */
}
int main (void) {
int a[][7] = {{ 0, 9, 3, 6, 4, 8, 3 },
/* { 3, 9, 2, 7, 9, 1, 6 }, uncomment for test */
{ 6, 1, 5, 2, 6, 3, 4 },
{ 4, 3, 3, 8, 1, 2, 5 },
{ 3, 9, 2, 7, 9, 1, 6 }},
maxidx;
long sum = 0;
size_t nrow = sizeof a/sizeof *a;
if ((maxidx = maxrow (a, nrow, &sum)) != -1)
printf (" max sum '%ld' occurs at row : %d (0 - indexed).\n",
sum, maxidx);
return 0;
}
Example Use/Output
For the unique sum case:
$ ./array2Drow
max sum '37' occurs at row : 3 (0 - indexed).
non-unique case:
$ ./array2Drow
no unique max.
Look it over and let me know if you have any questions, or if I misinterpreted your needs.

Return the sub-array of the maximum sum

In the book "elements of programming interviews", I came across, the problem of returning the subarray of the maximum sum. I tried their solution and I don't think we need to keep track of the minimum sum to get the array of the maximum sum:
I wrote another version of it maximumSumMine where I removed the minSum and it worked fine, the output in the comments
What is the purpose of tracking minSum, do we really need it?
#include <stdio.h>
#include <limits.h>
typedef struct range {
int start;
int end;
int maxSum;
} range;
void print(int *a, int start, int end) {
for (int i = start; i <= end; i++) {
printf("%d ", a[i]);
}
printf("\n");
}
// Book's code as it is
range maximumSum(int *a, int n) {
range r;
r.start = 0; r.end = 0;
int minSum = 0, sum = 0, minIndex = -1, maxSum = INT_MIN;
for (int i = 0; i < n; i++) {
sum += a[i];
if (sum < minSum) {
minSum = sum;
minIndex = i;
}
if (sum - minSum > maxSum) {
maxSum = sum - minSum;
r.start = minIndex + 1;
r.end = i + 1;
}
}
return r;
}
range maximumSumMine(int *a, int n) {
range r;
r.start = 0; r.end = 0;
int sum = 0, minIndex = -1, maxSum = INT_MIN;
for (int i = 0; i < n; i++) {
sum += a[i];
if (sum < 0) {
sum = 0;
minIndex = i + 1;
}
if (sum > maxSum) {
maxSum = sum;
r.start = minIndex;
r.end = i;
}
}
return r;
}
void unitTests() {
// Example 1
int a[5] = {-2, 5, 1, -1, 4};
range r = maximumSum(a, 5);
print(a, r.start, r.end); // output 5 1 -1 4 0
// Example 2
int b[5] = {2, -5, 5, -1, 3};
r = maximumSum(b, 5);
print(b, r.start, r.end); // 5 -1 3 1
// Example 1
r = maximumSumMine(a, 5);
print(a, r.start, r.end); // output 5 1 -1 4
// Example 2
r = maximumSum(b, 5);
print(b, r.start, r.end); // 5 -1 3 1
}
int main() {
unitTests();
return 0;
}
You need the minimum sum because the algorithm involves computing prefix sums:
sums[i] = a[0] + a[1] + ... + a[i]
So for each i, the maximum sum you can get that ends at a[i] is sums[i] - min(sums[j < i]).
The book code implements this without actually using an array, as you can simply keep track of the minimum and the current prefix sum.
If you only take the max of the prefix sums under the conditions that you do, it will not work for negative maximum sums: you will always output 0 if the maximum sum is negative, because you will set your prefix sum to 0 when it becomes negative.
Sometimes, ignoring negative maximum sums can be perfectly fine, other times not. I've seen both versions given as programming assignments / questions.
Example:
a = {-1, -2, -3}
book output = -1
your output = 0

Resources