printing grid with specified dimension with n*n - c

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).

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.

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");
}

I want to print out the following to the console

I want to print out the following to the console:
+++++
++++*
+++**
++***
+****
*****
I am a new learner of programming, so encountering some difficulties. Can anyone help me, please? I have tried this, but is incorrect. What do I need to change?
#include<stdio.h>
int main(){
int i, j, k;
for(i=0; i<5; i++){
for(j=i; j<5; j++){
for(k=0; k<j; k++){
printf("*");
}
printf("+");
}
printf("\n");
}
return 0;
}
You have the right idea: Use three for loops.
#include <stdio.h>
int main() {
for (int i = 0; i < 6; i++) {
for (int k = i; k < 5; k++) {
printf("+");
}
for (int j = 0; j < i; j++) {
printf("*");
}
printf("\n");
}
return 0;
}
Test
+++++
++++*
+++**
++***
+****
*****
Online demo
First, generalise it and wrap it in a function. You want a square with a diagonal. It has to be an even number of characters to look right. But + and * could be any character, and the size could be 6 or all the way up to screen maximum width.
so
/* print a square with a diagonal
N - the size of the sides of the square
cha - character a (eg '+')
chb - character b (eg '*')
*/
void printdiagsquare(int N, char cha, char chb);
That's our prototype, and that's half the battle.
Now we need to check N is even and positive, then write the loops.
Let's get the test away first.
if(N < 2 || (N % 2) == 1)
printf(N must be even\n");
Now the main loop for each line
for(i=0;i<N;i++)
{
//printline code here
printf("\n");
}
Now test it. Is it printing N blank lines?
main(void)
{
printdiagsquare(6, '+', '*');
}
Now to get the lines printed.
to print N-1 '+'s is easy. We need j as the counter since i is the outer
for(j=0;j<N-1;j++)
printf("%c", cha);
But we need to generalise, we need to print 6,, 5, 4, 3 and so on as i increases.
So
for(j=0;j<N-i-1;j++)
printf("%c", cha);
I'll leave the last little bit for you to do. No point just typing ina function blindly.
You could try more optimized code for m-rows and n-columns
in 2 for loop only :-
#include <stdio.h>
int main(void) {
int m = 6; // Rows
int n = 5; // Cols
int i,j,k;
for (i = 0; i < m; i++) {
k = i;
for (j = n; j >= 0; j--) {
if(k>=j)
printf("*");
else
printf("+");
}
printf("\n");
}
return 0;
}

How to fill a two dimensional array with chars in 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.

Remove white space at the end of the output in C

The following code is for printing the elements of a matrix in spiral order. The program works fine. The problem, however, is that the online compiler against which I'm checking the program, doesn't accept trailing white spaces at the end of the output. Could anyone give me some ideas as to how I can get around the last white space being added at the output?
For reference, my code is as follows (yes the variable names are terrible. I'm working on changing my habit of putting random variable names!!)
#include <stdio.h>
int main()
{
int a[6][6];
int i, k = 0, l = 0, m=3, n=3, j;
scanf("%d %d",&m, &n);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
}
while (k < m && l < n)
{
for (i = l; i < n; ++i)
printf("%d ", a[k][i]);
k++;
for (i = k; i < m; ++i)
printf("%d ", a[i][n-1]);
n--;
if ( k < m)
{
for (i = n-1; i >= l; --i)
printf("%d ", a[m-1][i]);
m--;
}
if (l < n)
{
for (i = m-1; i >= k; --i)
printf("%d ", a[i][l]);
l++;
}
}
return 0;
}
Input:
1 2 3
4 5 6
7 8 9
Output:
1 2 3 6 9 8 7 4 5{one extra space}
Any way to fix this problem?
(Also sorry for the terrible formatting. First question on StackOverflow!)
You can put an if condition in your for loops
for (i = l; i < n; ++i)
{
printf("%d", a[k][i]);
if(i < n-1)
printf(" ");
}
You need to suppress the space when you don't need one.
You can do it like this:
Add these declarations:
char *format = "%d";
int first_number = 1;
Add this after the first printf:
if (first_number) {
/* Now we want a space between numbers */
first_number = 0;
format = " %d";
}
Change your printf:s to use the new variable:
printf(format, ...);
Looking at your code, this for (the first one in the while loop):
for (i = l; i < n; ++i)
printf("%d ", a[k][i]);
will always be executed at least ones (because l<n, coming from the while's condition).
Then you can just do the following:
always add the space in front of the number
add a single if check just for this very first for-loop (use some bool flag).
For example, something like:
bool first = true;
while (k < m && l < n)
{
for (i = l; i < n; ++i)
{
if( ! first )
{
printf(" %d", a[k][i]);
}
else
{
printf("%d", a[k][i]);
first = false;
}
}
// ....
}
This will be rather efficient and short solution - the if is in just one loop and the flag will be true just once (will avoid cache misses).
You can set a boolean variable isFirst to true before your printing out any stuff, and test it before each printf statement. If isFirst, do not print a space but set isFirst to false; else print a single space. After that, continue with printing your number without a space.
Alternative: Instead of printing your results immediately, create a results array. Store your results in there, and when done, print out the results in a tight loop. You can print the first number without a leading space, then loop over the remainder and print them with a leading space.
the printf() statement,
printf("%d ", a[k][i]);
results in extra space. use
"%d"
without space or use space in the begining as,
" %d"
then at the end there wont be a extra space.
its about how you use space in your printf(). use space in a way that extra space is not present at the end as you wanted.
You can use code like this,
while (k < m && l < n)
{
for (i = l; i < n; ++i)
{
if(l==0&&i==0)
{
printf("%d", a[k][i]);
}
else
printf(" %d", a[k][i]);
}
k++;
for (i = k; i < m; ++i)
printf(" %d", a[i][n-1]);
n--;
if ( k < m)
{
for (i = n-1; i >= l; --i)
printf(" %d", a[m-1][i]);
m--;
}
if (l < n)
{
for (i = m-1; i >= k; --i)
printf(" %d", a[i][l]);
l++;
}
An answer after accepted answer:
Rather than:
while (k < m && l < n) {
...
printf("%d ", a[k][i]);
...
printf("%d ", a[i][n-1]);
...
printf("%d ", a[m-1][i]);
...
printf("%d ", a[i][l]);
...
}
Change the format.
const char *format = "%d";
while (k < m && l < n) {
...
printf(format, a[k][i]);
format = " %d";
...
printf(format, a[i][n-1]);
...
printf(format, a[m-1][i]);
...
printf(format, a[i][l]);
...
}
fputc('\n', stdout); // if desired.

Resources