Here is my code
#include<stdio.h>
void main() {
int a[4][4] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 15, 6, 5 },
{ 4, 3, 2, 1 } };
int max = a[0][0];
int mIndexF, mIndexE, addition = 0, multiplication = 1, i, j, status = 0, k,
l;
// this is for find out maximum value
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
if (max < a[i][j]) {
max = a[i][j];
mIndexF = i;
mIndexE = j;
}
}
}
for (k = 0; k < 4; k++) {
for (l = 0; l < 4; l++) {
if ((a[k][l] < max) && (status == 0)) {
addition += a[k][l];
} else {
status++;
if (a[k][l] != max) {
multiplication *= a[k][l];
}
}
}
}
printf("Addition is %d\n", addition);
printf("Multiplication is %d", multiplication);
return 0;
}
I want to find the maximum value. Also want to print addition of the values which are in before of the maximum value and want to print multiply value of the values which are in after the maximum value.
The following should do the trick:
#define MAX_INT (((unsigned int)(-1))>>1)
#define MIN_INT (~(MAX_INT))
void minmax(int a[4][4])
{
int i, j, maxi=0, maxj=0, max=MIN_INT, sum=0, mul=1;
// this is for find out maximum value
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
if (max < a[i][j]) {
max = a[i][j];
maxi = i;
maxj = j;
}
}
}
// this is to add and multiply
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
if (i< maxi || (i==maxi && j<maxj)) // this is "before"
sum += a[i][j];
else if (i==maxi && j==maxj) // this is "same"
; //..nothing to do
else mul *= a[i][j];
}
}
printf("i,j=%d,%d; sum= %d, mul= %d\n", maxi, maxj, sum, mul);
}
EDIT: Added definitions of MAX_INT and MIN_INT
Your code seems to be correct: just initialize
max=INT_MIN using include<limits.h>
Your second loops seems to slight inappropriate you could use:
for(i=0;i<4;i++)
for(j=0;j<4;j++)
{
if(status==0)
add+=disp[i][j];
else if(status==1)
mul*=disp[i][j];
if(i==loc_i && j==loc_j)
status=1;
}
Afterwards just subtract
add-=disp[mIndexF][mIndexE];
#include<stdio.h>
void main(){
int a[4][4]={
{10,11,12,13},
{14,15,16,17},
{18,19,20,21},
{22,2,3,3}
};
int max = a[0][0],mIndexF,mIndexE,addition = 0,multiplication = 1,i,j,status=0,k,l;
// this is for find out maximum value
for(i=0;i<4;i++){
for(j=0;j<4;j++){
if(max<a[i][j]){
max = a[i][j];
mIndexF=i;
mIndexE=j;
}
}
}
printf("The maximum value is %d\n", max);
for(k=0;k<4;k++){
for(l=0;l<4;l++){
if((a[k][l]<max) &&(status==0)){
addition+=a[k][l];
}else{
status++;
if(a[k][l]!=max){
multiplication*=a[k][l];
}
}
}
}
printf("Addition is %d\n",addition);
printf("Multiplication is %d",multiplication);
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.