How to fill a two dimensional array with chars in C? - c

The point of the code is to create a 2D array of dimensions set by the user. After being prompted for the width and height, the user must put in char values into each position in the 2D array. When implemented with int: (int mat, int value), the algorithm works fine, however when trying to implement with char(char mat, char value), the output is not consistent with the integer version. The only changes are the type of array and value, as well as setting the scanf/printf("%d") to scanf/printf("%c). Any way you can implement this 2D array with chars?
#include <stdio.h>
int main() {
int width;
int height;
printf("Enter col and row values between 2 and 20.\n");
scanf("%d %d", &width, &height);
printf("The numbers you typed was %d %d\n", width, height);
char mat[height][width];
int i;
int j;
char value;
for (i = 0; i < height; i++) {
for (j = 0; j < width; j++) {
printf("Enter your value.\n");
scanf("%c", &value);
mat[i][j] = value;
}
}
for (i = 0; i < height; i++) {
for (j = 0; j < width; j++) {
printf("%c", mat[i][j]);
}
printf("\n");
}
return 0;
}

... the output is not consistent with the integer version
Well, of course not. It will be characters rather than integers. Otherwise, it will be the same.
Also, your input loop is really weird.
for (i = 0; i < height; i++) {
for (j = 0; j < width; j++) {
printf("Enter your value.\n");
scanf("%c", &value);
mat[i][j] = value;
}
}
It seems like you're trying to prompt for each character, but then you only read a single character. I can't imagine how you expect anyone to use that. If I want to put in an "A", I type "A", but then nothing will happen until I press enter. But that will input two characters. So this code seems somewhat poorly designed.
As a quick fix, you could try something like:
for (i = 0; i < height; i++) {
for (j = 0; j < width; j++) {
printf("Enter your value.\n");
do scanf("%c", &value);
while (value == '\n' || value == '\r');
mat[i][j] = value;
}
}

Change this statement the following way
scanf(" %c", &value);
^^^^
Also change this statement something like
printf("Enter your character value: ");
that it would be more clear what the program expects to be entered.

Related

Input for 2D character array in C

I am new to C programming....we have 2D arrays for integers...but how to declare and take the input for 2D string arrays...I tried it for taking single character input at a time similar to integer array...but I want to take whole string as input at a time into 2D array..
code:
#include <stdio.h>
int main()
{
char str[20][20];
int i, j;
for (i = 0; i < 20; i++)
{
for (j = 0; j < 20; j++)
{
scanf("%c", &str[i][j]);
}
}
}
can anyone resolve this problem?
The declaration of a 2D string array can be described as:
char string[m][n];
where m is the row size and n is the column size.
If you want to take m strings as input with one whole string at a time...it is as follows
#include<stdio.h>
int main()
{
char str[20][20];
int i,j;
for(i=0;i<m;i++)
{
gets(str[i]);
}
}
here 'i' is the index of the string....
Hope this answer helps...
A few issues with your code. Using scanf to reach characters, you're going to read newlines. If I create a more minimal version of your code with an extra few lines to print the input, we can see this:
#include <stdio.h>
int main() {
char str[3][3];
int i, j;
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
scanf("%c", &str[i][j]);
}
}
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf("%c ", str[i][j]);
}
printf("\n");
}
}
And running it:
$ ./a.out
gud
ghu
ert
g u d
g h
u
e
$
We can test the input to circumvent this. If the character input is a newline character ('\n') then we'll decrement j so effectively we've sent the loop back a step. We could easily extend this boolean condition to ignore other whitespace characters like ' ' or '\t'.
#include <stdio.h>
int main() {
char str[3][3];
int i, j;
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
char temp = 0;
scanf("%c", &temp);
if (temp == '\n' || temp == ' ' || temp == '\t') {
j--;
}
else {
str[i][j] = temp;
}
}
}
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf("%c ", str[i][j]);
}
printf("\n");
}
}
Now,, when we run this:
$ ./a.out
gud
ghu
ert
g u d
g h u
e r t
$
Of course, one other thing you should do is to check the return value of scanf, which is an int representing the number of items read. In this case, if it returned 0, we'd know it hadn't read anything. In that case, within the inner loop, we'd probably also want to decrement j so the loop continues.
#include<stdio.h>
main()
{
char name[5][25];
int i;
//Input String
for(i=0;i<5;i++)
{
printf("Enter a string %d: ",i+1);
}
//Displaying strings
printf("String in Array:\n");
for(int i=0;i<5;i++)
puts(name[i]);
}
Simple code that accepts String in an array.

Read words from keyboard into a C 2D array

I would need some help after googling like 2 hours with no luck. (Maybe i'm just formulating my question incorrectly?)
I need to read 10 words from keyboard, and show a warning if any of the last 9 words are bigger than the first word.
I know how to use strlen to determine the last part of the request, but I have no idea how to do the first one.
My code looks like this:
const int ARRAY_SIZE = 10;
const int MAX_WORD_SIZE = 101;
int main() {
char arr[ARRAY_SIZE][MAX_WORD_SIZE];
for (int i = 0; i < ARRAY_SIZE; ++i) {
for (int j = 0; j < MAX_WORD_SIZE; ++j) {
printf("Add word %d:\n", i+1);
scanf("%s", arr[i][j]);
}
}
return 0;
}
But it does not work. cLion tell me "Format specifies type 'char *' but the argument has type 'int'".
I really don't understand why this doesn't work.
"%s" expects a memory address to where it is supposed to start saving the string.
You have a two dimensional array arr[ARRAY_SIZE][MAX_WORD_SIZE];. When you use [] once you get a 1-dimension array, which is what %s expects.
But since you are using [] twice, you are getting a single element of that array type, which is char.
change your scanf to: scanf("%s", arr[i]); to fix that.
Having noticed that, you can get rid of the inner for loop and variable j.
for (int i = 0; i < ARRAY_SIZE; ++i) {
printf("Add word %d:\n", i+1);
scanf("%s", arr[i]);
}
The solution to your problem would be:
const int ARRAY_SIZE = 10;
const int MAX_WORD_SIZE = 101;
int main() {
char arr[ARRAY_SIZE][MAX_WORD_SIZE];
for (int i = 0; i < ARRAY_SIZE; ++i) {
printf("Add word %d:\n", i+1);
scanf(" %s", arr[i]);
}
return 0;
}
It is a good practice to put a blank space in " %s". This way, chars such us \n are ommited, and many problems which stem from here are avoided.
If you wanted to do
for (int i = 0; i < ARRAY_SIZE; ++i) {
for (int j = 0; j < MAX_WORD_SIZE; ++j) {
printf("Add word %d:\n", i+1);
scanf("%s", arr[i][j]);
}
}
you would be reading character by character, so you would have to do instead:
for (int i = 0; i < ARRAY_SIZE; ++i) {
for (int j = 0; j < MAX_WORD_SIZE; ++j) {
printf("Add word %d:\n", i+1);
scanf("%c", arr[i][j]);
}
}
This way of solving the problem may give rise to another problem: not all words have the maximum size so this would be fixed by:
for (int i = 0; i < ARRAY_SIZE; ++i) {
for (int j = 0; j < MAX_WORD_SIZE; ++j) {
printf("Add word %d:\n", i+1);
scanf("%c", arr[i][j]);
if(arr[i][j]=='\n'){
break;
}
}
}
Anyway, the first one is the best solution.

To printf a matrix

When i want to print a matrix which i input,i can use code:
#include <stdio.h>
int main(void)
{
int n, m; //row and column
printf("Enter row and column:\n");
scanf("%d %d", &n, &m);
int x[n][m];
printf("Enter your matrix:\n");
for (int i = 0; i < n; i++) //input my matrix
{
for (int j = 0; j < m; j++)
{
scanf("%d", &x[i][j]);
}
}
printf("print it:\n");
for (int i = 0; i < n; i++) //print it
{
for (int j = 0; j < m; j++)
{
printf("%d ", x[i][j]);
}
putchar('\n');
}
}
enter image description here(a possible case)
In code above, I have to assign values to the rows and columns of the matrix,which named "n" and "m".
int n, m;
scanf("%d %d", &n, &m);
But now I am asking a way to automatic tally .
Can I get this one directly?
enter image description here
You can simulate a two-dimensional array with a one-dimensional array, if that's what you mean:
#include <stdio.h>
#include <stdlib.h>
#define DIGITS 3
int main(void) { // It's good practice to fill function arguments with void if not planning on using them
/* scanf("%d %d", &n, &m); Using scanf with uninitialised variables will result in
* undefined behaviour if it is unable to convert the input. Using fgets
* is easier to debug, safer, and cleaner.
* I highly recommend this: http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html
*/
char buf[DIGITS+1];
printf("%s", "Enter array rows:");
fgets(buf, DIGITS+1, stdin);
const int n = atoi(buf);
printf("%s", "Enter array columns:");
fgets(buf, DIGITS+1, stdin);
const int m = atoi(buf);
int x[n*m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
printf("Enter array value at %d, %d: ", i, j);
fgets(buf, DIGITS+1, stdin);
x[i+j] = atoi(buf);
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
printf("%d ", x[i+j]);
}
printf("\n");
}
}
I'm not really sure as to why you would do this when C supports your two-dimensional array answer equally.
But now I am asking a way to automatic tally. Can I get this one directly?
Yes.
Form a linked-list of lines. Initially the list is empty.
Read the first line of input, the "1 2 3" into a string. Use fgets().
Parse the line to detect the number of values in it.
Append the line to the linked list of lines.
Continue doing so until 1) end-of-file, 2) a blank line or 3) number of integer is not the same as the first (error condition).
Now code has the m (number of values per line) and n, the number of lines.
Form int x[n][m];
Parse the lines for values and save in x.

Inputing and printing a 2D array

I am just starting to dive into 2D arrays and I am having some trouble why my output is producing a line of data rather than the dimensional matrix. All help is appreciated! Thank you!!
My code:
#include <stdio.h>
#include <stdlib.h>
int main() {
int x, y, i, j;
int m[10][10];
setvbuf(stdout, NULL, _IONBF, 0);
while (1) {
printf("Number of rows? ");
scanf("%d", &x);
if (x == 0)
break;
printf("Number of columns? ");
scanf("%d", &y);
printf("Enter matrix values row by row: \n");
for (i = 0; i < x; i++) {
for (j = 0; j < y; j++) {
scanf("%d", &(m[i][j]));
}
}
printf("Matrix read:\n");
for (i = 0; i < x; i++) {
for (j = 0; j < y; j++) {
printf("%d", m[i][j]);
}
}
Imputed data:
Number of rows? 2
Number of columns? 2
Enter matrix values row by row:
1 2 3 4
Output:
Matrix read:
1234
To figure out why your current program is printing the line, go through the printing loop, and look at all points where you are printing the values.
You will notice that it will be something like this:
print "1", print "2", print "3", print "4".
So, the program just does that. It prints the numbers without any other "formatting" around.
You can do something like this:
printf("Matrix read:\n");
for (i = 0; i < x; i++) {
for (j = 0; j < y; j++) {
printf("%d ", m[i][j]);
}
printf("\n");
}
Notice there's a space after the number in the literal "%d ".
And then, notice that a new line is printed after every inner for loop (which corresponds to a row).
Note: You may want to use more descriptive names. Eg: row instead of x
and column instead of y.
Your program is perfectly fine. It is printing the matrix in correct order too. However if you just want to format the output in a matrix format, just print "\t" and "\n" after the inner and outer loop respectively.
for (i = 0; i < x; i++) {
for (j = 0; j < y; j++) {
printf("%d\t", m[i][j]);
}
printf("\n");
}

printing grid with specified dimension with n*n

I am trying to create a grid of, for example, 4 rows and 4 columns.The dimension of the grid is n*n size. I have tried the following piece of code which is working fine for 3 rows only as I am trying to print 4*4 grid. But the last grid (4th is this case) is never printed. I mean as soon as the 3rd grid is printed the loop exits. I would appreciate if anyone help me to figure out why it is taking only 3 rows with 4 columns rather than 4 rows with 4 columns? Here is what I have tried so far,
void main()
{
int n, i, j;
scanf("%d", &n);
char grid[n][n];
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
scanf("%c", &grid[i][j]);
}
}
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (grid[i][j] == '9')
printf("X");
else
printf("%c", grid[i][j]);
}
}
}
This is a very quick hack to get your code working, as I believe you expect. Including the \n in scanf is probably not the best way of doing this, please see this answer:
int n, i, j;
scanf("%d\n", &n);
char grid[n][n];
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
scanf("%c", &grid[i][j]);
}
}
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (grid[i][j] == '9')
printf("X");
else
printf("%c", grid[i][j]);
}
printf("\n");
}
Using this as input:
4
1234234534564567
This is the output:
1234
2345
3456
4567
The line
scanf("%c", ...)
will also read any newline chars typed, including the one following the previous
scanf("%d", ...)
So if you enter each line's data followed by a newline, you will have read 1 + 3 * 5 = 16 characters after the third line.
I suggest you input four strings instead, and copy each character to the array, using scanf("%s", ...). That way, all whitespace will be ignored (except the final newline will remain in the input buffer).

Resources