Printing a 2D Array with User Input in C

Dec 07, 2025 · Programming · 9 views · 7.8

Keywords: C programming | 2D array | user input | for loop | scanf

Abstract: This article details how to use the scanf function and for loops to print a user-defined 2D array in C. By analyzing the best answer code, it explains core concepts of array declaration, input handling, and loop traversal, and discusses potential extended applications.

Introduction

In C programming, 2D arrays are essential data structures for handling matrix and grid data. Users often need to dynamically generate and print array contents based on input. Based on a common question, this article explores how to use the scanf function to obtain user input and initialize and print a 2D character array using nested for loops.

Method Overview

Referencing the best answer, the core method involves declaring a fixed-size 2D character array, using scanf to read the number of rows and columns, and then traversing the array with nested loops to initialize each element as the dot character '.' and print it. The code example is as follows:

#include <stdio.h> #define MAX 10 int main() { char grid[MAX][MAX]; int i,j,row,col; printf("Please enter your grid size: "); scanf("%d %d", &row, &col); for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { grid[i][j] = '.'; printf("%c ", grid[i][j]); } printf("\n"); } return 0; }

This code first defines the maximum size MAX, then declares the 2D array grid. It uses scanf to obtain user input for rows row and columns col, ensuring the input does not exceed MAX to prevent array overflow. The nested loops iterate from 0 to row-1 and col-1, setting each element to '.' and printing it, with a newline after each row.

Discussion and Extensions

The original question mentioned more complex tasks, including using fgets to handle word lists. Although this code does not implement it, it can be extended: for example, after initializing the array, fgets can be used to read words and store them in the array, or the printing logic can be modified to match specific formats. Additionally, error handling should be considered, such as input validation and array boundary checks.

Conclusion

This article demonstrates the basic method of printing a 2D array in C through a simple example. Key points include array declaration, user input handling, and loop control. After mastering these fundamentals, one can further extend to more complex applications, such as dynamic memory allocation or string operations.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.