Yêu cầu:
Tính tổng các giá trị lẻ trong mảng số nguyên
Thuật toán:
1. Viết hàm nhập vào ma trận
2. Viết hàm tính tổng các phần tử lẻ trong ma trận số nguyên
Code:
/*****Sum all of odd elements in matrix******** *Author: vncoding *Date : 31/03/2019 *****************************************************/ #include <stdio.h> #include <conio.h> #include <stdlib.h> #define N 100 #define M 100 void ImportData(int[][M], int, int, char*); void PrintMatrix(int[][M], int, int); int SumOddInMatrix(int A[][M], int, int); void main() { int nRow, nCol; int A[N][M]; printf("\nNumber of row: "); scanf("%d", &nRow); printf("\nNumber of column: "); scanf("%d", &nCol); ImportData(A, nRow, nCol, "A"); PrintMatrix(A, nRow, nCol); printf("\nSum all of odd elements in matrix: %d", SumOddInMatrix(A, nRow, nCol)); getch(); } /************************************************************* * Function : SumOddInMatrix() * Parameter : A[][M]: input matrix (I) nRow : row number (I) nCol : column number(I) * Return : int * Description : Sum of odd element in matrix *************************************************************/ int SumOddInMatrix(int A[][M], int nRow, int nCol) { int iRow, iCol; int sum = 0; for (iRow = 0; iRow < nRow; iRow++) { for (iCol = 0; iCol < nCol; iCol++) { if ((A[iRow][iCol] %2) != 0) sum += A[iRow][iCol]; } } return sum; } /************************************************************* * Function : ImportData() * Parameter : A[][M]: input matrix (I) nRow : row number (I) nCol : column number(I) nameMatrix: matrix name (I) * Return : void * Description : Import matrix data *************************************************************/ void ImportData(int Matrix[][M], int nRow, int nCol, char* nameMatrix) { int iRow, iCol; for (iRow = 0; iRow < nRow; iRow++) for (iCol = 0; iCol < nCol; iCol++) { printf("\n%s[%d][%d] = ", nameMatrix, iRow, iCol); scanf("%d", &Matrix[iRow][iCol]); } } /************************************************************* * Function : PrintMatrix() * Parameter : Matrix: input matrix (I) nRow : row number (I) nCol : column number(I) * Return : void * Description : Display matrix data *************************************************************/ void PrintMatrix(int Matrix[][M], int nRow, int nCol) { int iRow, iCol; printf("\nA = "); for (iRow = 0; iRow < nRow; iRow++) { printf("\n"); for (iCol = 0; iCol < nCol; iCol++) { printf("\t%d\t", Matrix[iRow][iCol]); } } }
Kết quả:
Number of row: 3
Number of column: 4
A[0][0] = 3
A[0][1] = 4
A[0][2] = 8
A[0][3] = 12
A[1][0] = 9
A[1][1] = 45
A[1][2] = 34
A[1][3] = 12
A[2][0] = 87
A[2][1] = 45
A[2][2] = 10
A[2][3] = 23
A =
3 4 8 12
9 45 34 12
87 45 10 23
Sum all of odd elements in matrix: 212
Leave a Reply
You must be logged in to post a comment.