顺时针输出一个二维数组 c语言实现 和 java实现

本文介绍了如何使用C语言和Java实现二维数组的顺时针输出。通过提供两种语言的代码示例,分别展示了如何对一个3x3的矩阵进行顺时针打印元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一个二维数组: int mat[2][2]={{1,2},{3,4} };

正常输出顺序为 1 2 3 4 

顺时针输出为: 1 2 4 3 

 

java实现

public class test {
    static void printMat(int mat[][],int i,int j){
        int count = 1;
        int max = i -1;
        for (int m = 0; m < j; m++){
            System.out.print(mat[0][m]);
        }
        for (int n = 1; n < i; n++){
            System.out.print( mat[n][j-1]);
        }

        while (max>0){
            
            if (count % 2 != 0){
                for (int a = j - 1-1; a>=0; a--){
                    System.out.print(mat[max][a]);
                }
            }
            else{
                for (int b = 0; b <= j - 1-1; b++){
                    System.out.print( mat[max][b]);
                }
            }
            count++;        max--;
            
        }
        
        
    }
    public static void main(String[] args) {
        int mat[][]= {{1,2,3},{4,5,6},{7,8,9}};
         printMat(mat,3,3);
        
    }
}

 

C原因语言实现:

#include<stdlib.h>
#include<stdio.h>

void printMat(int mat[3][3],int m,int n){
    int count = 1;
    int max = m -1;
    for (int i = 0; i < n; i++){
        printf("%d", mat[0][i]);
    }
    for (int j = 1; j < m; j++){
        printf("%d", mat[j][n-1]);
    }

    while (max>0){
        
        if (count % 2 != 0){
            for (int a = n - 1-1; a>=0; a--){
                printf("%d", mat[max][a]);
            }
        }
        else{
            for (int b = 0; b <= n - 1-1; b++){
                printf("%d", mat[max][b]);
            }
        }
        count++;        max--;
        
    }
    
    
}

int main(){
    int mat[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, {7,8,9} };
    printMat(mat, 3, 3);
    system("pause");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值