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.
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
There is a pointer array in the following code (char * newName) which is giving me some trouble. I believe the issue is somewhere between the backslashes i used to create barriers below. I have attached a picture below. All of the output is working correctly, however, there are 3 outputs of strings right under the word "santiago" that all begin with a strange unicode character and I am stumped as to why that is happening. The letters that come after the strange character (tbuq, bwi, etc) are all correct as well, so I just need to get rid of that character. I would greatly appreciate some guidance here
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int compare(const void* a, const void* b)
{
return strcmp(*(const char**)a, *(const char**)b);
}
void sort(char* names[], int n)
{
qsort(names, n, sizeof(char*), compare);
}
int main()
{
int i, j, k, n;
char alphabet[26];
for(i = 0; i < 26; i++)
{
alphabet[i] = i + 97;
}
char newAlphabet[26];
printf("input the new alphabet\n");
for(i = 0; i < 26; i++)
{
scanf(" %c", &newAlphabet[i]);
}
printf("How many names will you input?");
scanf(" %d", &n);
char * names[n];
printf("Enter the names: \n"); //erase before submitting
//the user will now enter the names one by one
for (i = 0; i < n; i++)
{
names[i] = (char *) malloc(100 * sizeof(char)); //allocating memory of 100 for each name pointer
if (names[i] == 0)
{
printf("Error.");
exit(1);
}
scanf("%s", names[i]);
}
for(i = 0; i < n; i++)
{
printf("%s\n", names[i]);
}
int nameConvert[n][100];
//convert the strings of names to their corresponding indexes based on the a = 0, b = 1, etc
for(k = 0; k < n; k++)
{
for(i = 0; i < (strlen(names[k])); i++)
{
for(j = 0; j < 26; j++)
{
if((*(names[k] + i)) == alphabet[j])
{
nameConvert[k][i] = j;
break;
}
}
}
}
////////////////////////////////////////////////////////////////////////////
char * newName[n];
for(i = 0; i < n; i++)
{
newName[i] = '\0';
}
for (k = 0; k < n; k++)
{
newName[k] = (char* ) malloc(100 * sizeof(char));
for(i = 0; i < (strlen(names[k])); i++)
{
char tempstr[2];
tempstr[0] = newAlphabet[nameConvert[k][i]];
tempstr[1] = '\0';
strcat(newName[k], tempstr);
}
printf("%s\n", newName[k]);
}
/////////////////////////////////////////////////////////////////////////////
for(i=0; i < n; i++)
{
for(j = 0; j < strlen(names[i]); j++)
{
printf("%d ", nameConvert[i][j]);
}
printf("\n");
}
sort(newName, n);
for(i = 0; i < n; i++)
{
printf("%s\n", names[i]);
}
return 0;
}
Since you are using strcat(), you have to ensure that the memory is zero (NULL) initialized, since we are talking about strings, of course. You can do it like this:
newName[k] = malloc(100 * sizeof(char));
newName[k][0] = '\0';
That way, you basically NULL-terminate the string in the first character, which means that you have an empty string. Then, you append your actual data to that string.
Without that step, you had a C string that was not NULL-terminated, something that the C string standard library needs in order to operate and know where the string ends.
Or follow #LinusGudmundsson suggestion (more expensive, since it will iterate over the 100 elements in order to initialize them all), and replace that malloc call with this:
newName[k] = calloc(100 , sizeof(char));
where the call to that method zero initializes the memory for you too. Read more in Difference between malloc and calloc?
The output you should get now (with either approach):
input the new alphabet
b j k v q z c d e t u h w x n o p f g l y m r s i a
How many names will you input?3
Enter the names:
jake amy santiago
jake
amy
santiago
tbuq
bwi
gbxlebcn
9 0 10 4
0 12 24
18 0 13 19 8 0 6 14
jake
amy
santiago
PS: Not the cause of the problem, but Do I cast the result of malloc? No.
I was having a problem with this part while doing one of my assignments. So I decided to do a simple program to store and see if my understanding is correct but I am still having the same problems.
Initially, I didn't make the arrays pointers but that caused the program to crash immediately. So that is also why they are char pointers. If anyone can also explain why they need to be pointers and why it prints the way it does, that would be immensely helpful.
#include <stdio.h>
int main() {
char arr[2][2];
char str[20];
for(int i = 0; i < 2; i++){
for (int j = 0; j < 2; j++){
printf("%s\n", "please put in a string: ");
scanf("%s\n", str[0]);
arr[i][j] = str[0];
}
}
for(int i = 0; i < 2; i++){
for (int j = 0; j < 2; j++){
printf("arr[%d][%d] == %s\n", i,j,arr[i][j]);
}
}
return 0;
}
the output that i got:
please put in a string:
pleasework
what
please put in a string:
s
please put in a string:
f
please put in a string:
g
arr[0][0] == f
arr[0][1] == f
arr[1][0] == f
arr[1][1] == f
Not the right outputs
If you want to just learn about:
"I'm having a hard time understanding the process for populating a multidimensional array."
then forget the string and the char, and do something simple, like use an int. The following code sample shows exactly that.
Simplest case: Populate multi-dim array of any type
#include <stdio.h>
int main() {
int arr[2][2];
int str;
for(int i = 0; i < 2; i++){
for (int j = 0; j < 2; j++){
printf("please put in a number [%d][%d]: ", i,j);
scanf("%d", &str);
arr[i][j] = str;
}
}
for(int i = 0; i < 2; i++){
for (int j = 0; j < 2; j++){
printf("arr[%d][%d] == %d\n", i,j,arr[i][j]);
}
}
return 0;
}
$ ./stackoverflow
please put in an number[0][0]: 1
please put in an number[0][1]: 2
please put in an number[1][0]: 34
please put in an number[1][1]: 450
arr[0][0] == 1
arr[0][1] == 2
arr[1][0] == 34
arr[1][1] == 450
Populate chars
If you want to use single characters, then you can use the following code also, BUT you have to take care. scanf works in mysterious ways. Notice how the space is there before the %c. That is to consume the \n that is there you press enter. You can read up here, but that was the reason for why you had to initially enter twice somet input and press enter. Frankly, I would use something else than scanf like fgets maybe, but since you used scanf, I showed the code which uses it also.
#include <stdio.h>
int main() {
char arr[2][2];
char str;
for(int i = 0; i < 2; i++){
for (int j = 0; j < 2; j++){
printf("%s", "please put in a character: ");
if (scanf(" %c", &str) == 1) { arr[i][j] = str; }
}
}
for(int i = 0; i < 2; i++){
for (int j = 0; j < 2; j++){
printf("arr[%d][%d] == %c\n", i,j,arr[i][j]);
}
}
return 0;
}
$ ./stackoverflow
please put in a character: a
please put in a character: b
please put in a character: c
please put in a character: d
arr[0][0] == a
arr[0][1] == b
arr[1][0] == c
arr[1][1] == d
Populate Strings
If you want to read strings, then you need to do it a little differently. You need not a 2 dimensional array. You need a 3-dimensional array because the strings are themselves char-arrays. Without a 3D-array you overwrote the 2D array and only got the last value printed multiple times. What was worse, since your multidimensional array is 2x2 while the input string is 1xn, and where n was greater than 2, you would have gotten buffer overflow. The following code fixes these.
#include <stdio.h>
#include <string.h>
int main() {
char arr[2][2][20];
char str[20];
for(int i = 0; i < 2; i++){
for (int j = 0; j < 2; j++){
printf("%s", "please put in a string: ");
if (scanf("%s", &str[0]) == 1)
{
// arr[i][j] = &str[0];
strncpy(arr[i][j], str, 20);
}
}
}
for(int i = 0; i < 2; i++){
for (int j = 0; j < 2; j++){
printf("arr[%d][%d] == %s\n", i,j, arr[i][j]);
}
}
return 0;
}
$ ./stackoverflow
please put in a string: ab
please put in a string: cd
please put in a string: ef
please put in a string: gh
arr[0][0] == ab
arr[0][1] == cd
arr[1][0] == ef
arr[1][1] == gh
And just for good measure, here is the 4th variation, which uses char* arr[2][2] instead of a 3D-char array. It doesn't change much, but like I said, just for good measure.
#include <stdio.h>
#include <string.h>
#include <malloc.h>
int main() {
char* arr[2][2];
char str[20];
for(int i = 0; i < 2; i++){
for (int j = 0; j < 2; j++){
printf("%s", "please put in a string: ");
if (scanf("%s", &str[0]) == 1)
{
arr[i][j] = (char*)malloc(20*sizeof(char));
strncpy(arr[i][j], str, 20);
}
}
}
for(int i = 0; i < 2; i++){
for (int j = 0; j < 2; j++){
printf("arr[%d][%d] == %s\n", i,j, arr[i][j]);
}
}
return 0;
}
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 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();
}