How do I print the elements of a 2D Char Array in C?
Here is my current code:
int main()
{
unsigned int size;
printf("Enter size:\n");
scanf("%d",&size);
char word[size][size];
//Enter the matrix
for(int k = 0; k < (size); ++k){
for (int j = 0; j < (size); ++j){
printf("Enter letter:");
scanf("%c",&word[k][j]);
}
}
//printf("\n");
for (int k = 0; k < size; ++k){
for(int j = 0; j < size; ++j){
printf("%c",word[k][j]);
}
//printf("\n ");
}
printf("\n");
}
When executed it returns the element in pairs (using a 4x4 array)
Example:
ab
cd
ef
gh
ij
kl
mn
op
Rather than my desired output:
abcd
efgh
ijkl
mnop
Why is this?
changing your scanf solves all the problems
scanf(" %c",&word[k][j]); // notice the space before '%c'
And also you need to change your printing loop to this
for (k = 0; k < size; ++k){
for(j = 0; j < size; ++j){
printf("%c",word[k][j]);
}
printf("\n");
}
Beware: %c and %1s do different things (apart from adding a terminating null for the latter):
c take every character including space, tab, cr and lf
%1s skip over all blanks (space, tab, cr, lf, etc.)
So at input time, you should use:
char c[2]; // provide room for a terminating null...
...
for(int k = 0; k < (size); ++k){
for (int j = 0; j < (size); ++j){
printf("Enter letter:");
scanf("%1s",c);
word[k][j] = c[0];
}
}
And at print time:
for (int k = 0; k < size; ++k){
for(int j = 0; j < size; ++j){
printf("%c",word[k][j]);
}
printf("\n "); // new line after each line
}
I removed the reading and it seems like printing is ok:
int main()
{
const unsigned int size = 4;
char word[size][size];
//Enter the matrix
for (int k = 0; k < (size); ++k) {
for (int j = 0; j < (size); ++j) {
word[k][j] = 'a' + j + (k * size);
}
}
for (int k = 0; k < size; ++k) {
for (int j = 0; j < size; ++j) {
printf("%c", word[k][j]);
}
printf("\n");
}
printf("\n");
getchar();
return 0;
}
And the output:
abcd
efgh
ijkl
mnop
I found two issues with your source.
One is the memory allocation - that is actually not ansi-c.
If you need dynamic memory you need to allocate it at runtime. Consider switching to c++ since there are standard facilities that help with that in a safer way.
The second issue was that there is a whitespace character in the buffer that is used as an input character. I think you want to clear that.
Here is the source with additional comments:
#include <stdio.h>
#include <stdlib.h>
void ansiC()
{
unsigned int size;
printf("Enter size:\n");
scanf("%d", &size);
//char word[size][size]; <- this is not ansi-c because size is unknown at compile time
char * word = (char*)malloc(sizeof(char)* size * size);
//Enter the matrix
for (int k = 0; k < (size); ++k)
{
for (int j = 0; j < (size); ++j)
{
printf("Enter letter:");
scanf("%c ", &word[k * size + j]);
//since word is just a pointer i changed the way the position is calculated
//after the character the user presses the enter key
//this puts a whitespace character on the buffer.
//by adding the space after %c you also clear that from the buffer
}
}
//printf("\n");
for (int k = 0; k < size; ++k)
{
for (int j = 0; j < size; ++j)
{
printf("%c", word[k * size + j]);
//since word is just a pointer i changed the way the position is calculated
}
//printf("\n ");
}
printf("\n");
free(word); //if you use malloc you need to remember to use free
}
int main()
{
ansiC();
return 0;
}
Please check this .
# include <iostream.h>
# include <conio.h>
void main()
{
clrscr();
char arr[5][3]={"abc","aks","tny","dkn","kbf"};
for(int a=0;a<5;a++)
{
for(int b=0;b<3;b++)
{
cout<<" "<<arr[a][b];
}
cout<<endl;
}
getch();
}
Related
My code never stops asking for input so I think I must've made an infinite loop, but I can't find where the error is. I've also noticed that when inserting the input line by line, it prints the result of one loop after inserting the first line of the second loop, which seems incorrect to me. Please help me debug. (For further context, the code is supposed to receive a number we'll call n, and then scan 3n more lines, which are basically n bundles of 3 similar lines. The 2nd and 3rd lines are two words with the same num of characters, and the 1st line is that num. The output is whether or not these words are anagrams.)
#include <stdio.h>
int main() {
int n, l;
scanf("%d\n", &n);
for (int i = 1; i <= n; i++) {
scanf("%d\n", &l);
char A[l], B[l];
for (int j = 0; j < l; j++) {
scanf("%c", &A[j]);
scanf("\n");
}
for (int j = 0; j < l; j++) {
scanf("%c", &B[j]);
scanf("\n");
}
for (int k = 0; k < l; k++) {
int result = 0;
for (int j = 0; j < l; j++) {
if (A[k] == B[j]) {
result = 1;
}
}
if (!result) {
printf("\nNO\n");
return 0;
}
}
printf("\nYES\n");
}
}
Example:
input:
2
6
listen
silent
4
Evil
live
output:
YES
NO
It's because you are asking for input over and over and over again,
Not sure what you are trying to achieve, but start by removing the extra scanfs
try this,
#include <stdio.h>
int main() {
int n, l;
scanf("%d\n", &n);
for (int i = 1; i <= n; i++) {
char A[l], B[l];
for (int k = 0; k < l; k++) {
int result = 0;
for (int j = 0; j < l; j++) {
if (A[k] == B[j]) {
result = 1;
}
}
if (!result) {
printf("\nNO\n");
return 0;
}
}
printf("\nYES\n");
}
}
Your scanf calls wait for an extra \n which requires more input to enter.
To fix this, remove the \n from your scanf calls. Also remove the extra calls when you enter A and B:
I have added some debug code to demonstrate where you are in your program execution while you enter your input.
#include <stdio.h>
int main() {
int n, l;
int res;
res=scanf("%d", &n);
printf ("res=%d, n=%d\n", res, n);
for (int i = 1; i <= n; i++) {
res = scanf("%d", &l);
printf ("res=%d, l=%d\n", res, l);
// char A[l], B[l];
char A[l+1], B[l+1];
for (int j = 0; j < l; j++) {
scanf(" %c", &A[j]);
}
printf ("A done\n");
for (int j = 0; j < l; j++) {
scanf(" %c", &B[j]);
}
printf ("B done\n");
A[l] = 0; B[l] = 0;
printf ("A=\"%s\" - B=\"%s\"\n", A, B);
...
Now your input should work properly.
But your code also contains another error.
You will treat "12344" and "11234" as correct match wchich is wrong.
To fix this you need to remove each matching character from B:
for (int k = 0; k < l; k++) {
int result = 0;
// We compare A[k] with the remaining characters in B only
for (int j = k; j < l; j++) {
if (A[k] == B[j]) {
result = 1;
B[j] = B[k]; // Replace matching character with non-matching character we checked earlier.
break;
}
}
if (!result) {
printf("\nNO\n");
return 0;
}
}
printf("\nYES\n");
This code stops as soon as the first match is found and removed that character from B.
The entries in B are rearranged to keep the unused entries at the end.
The full code looks like this:
#include <stdio.h>
int main() {
int n, l;
int res;
res=scanf("%d", &n);
printf ("res=%d, n=%d\n", res, n);
for (int i = 1; i <= n; i++) {
res = scanf("%d", &l);
printf ("res=%d, l=%d\n", res, l);
// char A[l], B[l];
char A[l+1], B[l+1];
for (int j = 0; j < l; j++) {
scanf(" %c", &A[j]);
}
printf ("A done\n");
for (int j = 0; j < l; j++) {
scanf(" %c", &B[j]);
}
printf ("B done\n");
A[l] = 0; B[l] = 0;
printf ("A=\"%s\" - B=\"%s\"\n", A, B);
for (int k = 0; k < l; k++) {
int result = 0;
for (int j = k; j < l; j++) {
if (A[k] == B[j]) {
result = 1;
B[j] = B[k];
break;
}
}
if (!result) {
printf("\nNO\n");
return 0;
}
}
printf("\nYES\n");
}
}
output:
~/stackoverflow$ ./test
4
res=1, n=4
2
res=1, l=2
12
A done
21
B done
A="12" - B="21"
YES
6
res=1, l=6
liver1
A done
evil1r
B done
A="liver1" - B="evil1r"
YES
3
res=1, l=3
111
A done
111
B done
A="111" - B="111"
YES
4
res=1, l=4
abcd
A done
dcbb
B done
A="abcd" - B="dcbb"
NO
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.
I spent hours in printing a lower triangle in C. However, I just cannot figure out how to solve this same question with array.
Below is one of the solution I found on net:
int main(void)
{
char ch='A';
int i,j;
for(i=1;i<7;i++)
{
for(j=0;j<i;j++)
printf("%c",ch++);
printf("\n");
}
return 0;
}
Below is how I try to do the same thing:
#define SIZE 8
int main(void){
char Alphabet[SIZE];
int i, j;
for (i = 0, j = 'A'; i < SIZE, j < 'A' + SIZE; i++, j++){
Alphabet[i] = j;
}
for (i = 0; i <= 7; i++){
for (j = 0; j <= i; j++){
printf("%c", Alphabet[j+i]);
}
printf("\n");
}
return 0;
}
The result of the code above is :
A
BC
CDE
DEFG
EFGHI
FGHIJK
GHIJKLM
HIJKLMNO
What should I revise if I want to print as follow:
A
BC
DEF
GHIJ
KLMNO
PQRSTU
Thank you.
Keep a track of elements printed from the Alphabet array so far and in the inner loop start printing from next element onward. You can do:
#include <stdio.h>
#define SIZE 26
int main(void) {
char Alphabet[SIZE];
for (int i = 0; i < SIZE; i++) {
Alphabet[i] = 'A' + i;
}
// Or simply have the Alphabet array initialized like this
// char Alphabet[SIZE] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int k = 0;
for (int i = 0; i < 6; i++) {
for (int j = 0; j <= i && k < SIZE; j++) {
printf("%c", Alphabet[k++]);
}
printf("\n");
}
return 0;
}
Output:
# ./a.out
A
BC
DEF
GHIJ
KLMNO
PQRSTU
EDIT:
In the comments, a fellow SO contributor said that the above approach is same as the one OP already found as a solution and OP might be looking for approach of calculating the Alphabet array index using i and j only and without use of variable keeping track of array index. Below is the program which does not use any extra variable to keep the track of Alphabet array index to print characters in inner loop and calculating the index using i and j:
#include <stdio.h>
#define SIZE 26
#define ARRLOC(x) ((x * ((x + 1) / 2)) + ((x % 2 == 0) ? (x / 2) : 0))
int main(void) {
char Alphabet[SIZE];
for (int i = 0; i < SIZE; i++){
Alphabet[i] = 'A' + i;
}
// Or simply have the Alphabet array declared like this
// char Alphabet[SIZE] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (int i = 0; i < 6; i++){
for (int j = 0; j <= i && (ARRLOC(i) + j) < SIZE; j++){
printf("%c", Alphabet[ARRLOC(i) + j]);
}
printf("\n");
}
return 0;
}
Output:
# ./a.out
A
BC
DEF
GHIJ
KLMNO
PQRSTU
You can just have a third 'index' variable that keeps track of which letter to output across both loops (I've called this k in the code below). Also, you need to make your Alphabet array bigger (26 seems like a reasonable number); then, if that k variable gets past 'Z', we can simply loop back to 'A' using the modulo operator (%):
#include <stdio.h>
#define SIZE 26
int main(void)
{
char Alphabet[SIZE];
int i, j, k;
for (i = 0; i < SIZE; i++) Alphabet[i] = 'A' + i;
int k = 0;
for (i = 0; i <= 7; i++) {
for (j = 0; j <= i; j++) {
printf("%c", Alphabet[k % 26]); // If past the end, loop back with the "%" operator
++k;
}
printf("\n");
}
return 0;
}
Or we can make the code a little more 'succinct' (though perhaps less clear) by initializing the k variable at the start of the outer loop and incrementing at the end of the inner loop:
for (k = i = 0; i <= 7; i++) { // Initialize "k" here ...
for (j = 0; j <= i; j++, k++) { // .. but increment it here!
printf("%c", Alphabet[k % 26]); // If past the end, loop back with the "%" operator
}
printf("\n");
}
If you want an 8 by 8 pyramid, you won't have enough characters to do it using the alphabet (requires 36), so I made the alphabet repeat itself (u could also make it go to numeric instead?)
#define SIZE 8
int area(int size);
int main(void){
char Alphabet[area(SIZE)];
int i, j;
for (i = 0, j = 'A'; i < area(SIZE); i++, j++){
if (j > 'Z') j = 'A';
Alphabet[i] = j;
}
int idx=0;
for (i = 0; i < SIZE; i++){
for (j = 0; j <= i; j++){
printf("%c", Alphabet[idx++]);
}
printf("\n");
}
return 0;
}
int area(int size) {
if (size==1) return 1;
return size + area(size - 1);
}
I'm new to C and I'm just trying to print out a two 2 array.
This bug has been annoying me all day and I'm not really sure whats going on.
#include<stdio.h>
void run(int);
main()
{
run(5);
return 0;
}
//Have to make it a character array as it needs to
//store numbers AND commas.
run(int x)
{
int size = 2*x -1;
char array[size][size];
int i = 0;
int j = 0;
for( i; i < size; i++){
for(j; j< size; j++){
array[i][j] = '1';
}
}
int k = 0;
int l = 0;
for( k; k < size; k++){
for(l; l< size; l++){
printf( "%c" , array[l][k]);
}
printf("%\n", "");
}
}
This is the output I get:
1%
%
%
%
%
%
%
%
%
You code has several mistakes:
The biggest problem is that your not initializing your loop counters where you should:
for(i; i < size; i++){
for(j; j < size; j++){
With that, i & j are left as they were prior to the for statement. The first section of these statements does nothing at all. While that's harmless for i (since it's initialized to 0 before the for), that's devastating for j, which never goes back to 0. Your code should be:
for(i = 0; i < size; i++){
for(j = 0; j < size; j++){
The same issue exists with k & l, and the same fix should be applied:
for(k = 0; k < size; k++){
for(l = 0; l < size; l++){
Next, you're "rotating" access in your array. When you fill the array with values, you have i in your outer loop and j in the inner loop, and you use them as [i][j]:
array[i][j] = '1';
Think of that as Out & In --> [Out][In].
When you print the array, you "rotate" that, k is outer & l is inner, and you use them as [l][k]:
printf("%c", array[l][k]);
That's like doing [In][Out].
While that's not a problem with all values being identical ('1'), and the matrix being square (width == height), it won't work with other values or dimensions, and is confusing.
Last, you're attempt to print a new line is wrong. You have a % specifier, but your not really using any valid character after that, and you don't need that anyway, just print:
printf("\n");
So, all together, here's what the code should be:
run(int x)
{
int size = 2*x -1;
char array[size][size];
int i,j;
for(i = 0; i < size; i++){
for(j = 0; j < size; j++){
array[i][j] = '1';
}
}
int k, l;
for(k = 0; k < size; k++){
for(l = 0; l < size; l++){
printf("%c", array[k][l]);
}
printf("\n");
}
}
(And as a side note, k & l are not really required, you can simply reuse i & j)
I have been searching all google or stackoverflow, but could not found it. :(
I have 100 strings, each string is a number with length = 100, the strings are seperated by a break_line.
Example of input:
010011001100..... (100 numbers)
...(98 strings)
0011010101010.... (100 numbers)
the ouput should be an array A[100][100] for each single number from the strings.
My codes do not work, could you please help to correct it:
#include <stdio.h>
char a[100][100];
int b[100][100];
int i,j;
int main(void)
{
for(i = 0; i < 100; i ++){
for(j = 0; j < 100; j ++){
scanf ("%s", a[i][j]);
b[i][j] = a[i][j] - '0';
printf("%d", b[i][j]);
}
printf("\n");
}
}
Thank you so much. !
Your code has two problems:
#include <stdio.h>
char a[100][100]; /* No space for the NUL-terminator */
int b[100][100];
int i,j;
int main(void)
{
for(i = 0; i < 100; i ++){
for(j = 0; j < 100; j ++){
scanf ("%s", a[i][j]); /* %s expects a char*, not a char */
b[i][j] = a[i][j] - '0';
printf("%d", b[i][j]);
}
printf("\n");
}
}
It should be
#include <stdio.h>
char a[100][101]; /* Note the 101 instead of 100 */
int b[100][100];
int i,j;
int main(void)
{
for(i = 0; i < 100; i ++){
scanf ("%s", a[i]); /* Scan a string */
for(j = 0; j < 100; j++){
b[i][j] = a[i][j] - '0';
printf("%d", b[i][j]);
}
printf("\n");
}
}
or
#include <stdio.h>
char a[100][100]; /* No need for space for the NUL-terminator as %s isn't used */
int b[100][100];
int i,j;
int main(void)
{
for(i = 0; i < 100; i ++){
for(j = 0; j < 100; j ++){
scanf (" %c", &a[i][j]); /* Scan one character, space before %c ignores whitespace characters like '\n' */
b[i][j] = a[i][j] - '0';
printf("%d", b[i][j]);
}
printf("\n");
}
}
I got the answer for my problem from Mr./Ms. BLUEPIXY.
It is
scanf("%1d", &b[i][j]);