Vấn đề
Viết chương trình C tính tổng và tích các phần tử mảng hai chiều bằng khởi tạo tại runtime.
Giải pháp
- Khởi tạo tại runtime (dynamic allocation) là cấp phát bộ nhớ lúc thực thi. Hàm
calloc()vàmalloc()hỗ trợ cấp phát động.
Chương trình tính tổng và tích các phần tử mảng 2D tại runtime.
Logic tính tổng:
printf("Sum array is : \n"); for(i=0;i<2;i++){ for(j=0;j<3;j++){ sum[i][j]=A[i][j]+B[i][j]; printf("%d\t",sum[i][j]); } printf("\n"); }
Logic tính tích:
printf("Product array is : \n"); for(i=0;i<2;i++){ for(j=0;j<3;j++){ product[i][j]=A[i][j]*B[i][j]; printf("%d\t",product[i][j]); } printf("\n"); } }
Ví dụ
#include<stdio.h> void main(){ //Khai báo mảng - runtime// int A[2][3],B[2][3],i,j,sum[i][j],product[i][j]; //Nhập phần tử mảng A và B// printf("Enter elements into the array A: \n"); for(i=0;i<2;i++){ for(j=0;j<3;j++){ printf("A[%d][%d] :",i,j); scanf("%d",&A[i][j]); } printf("\n"); } for(i=0;i<2;i++){ for(j=0;j<3;j++){ printf("B[%d][%d] :",i,j); scanf("%d",&B[i][j]); } printf("\n"); } //Tính tổng và in// printf("Sum array is : \n"); for(i=0;i<2;i++){ for(j=0;j<3;j++){ sum[i][j]=A[i][j]+B[i][j]; printf("%d\t",sum[i][j]); } printf("\n"); } //Tính tích và in// printf("Product array is : \n"); for(i=0;i<2;i++){ for(j=0;j<3;j++){ product[i][j]=A[i][j]*B[i][j]; printf("%d\t",product[i][j]); } printf("\n"); } }
Kết quả
Enter elements into the array A: A[0][0] :A[0][1] :A[0][2] : A[1][0] :A[1][1] :A[1][2] : B[0][0] :B[0][1] :B[0][2] : B[1][0] :B[1][1] :B[1][2] : Sum array is : 000 000 Product array is : 000 000