I am trying to print a char array on separate line for each element. This is what I have tried and neither way is working. I would like the output to look something like.

The array length is c c
The array length is o o
The array length is d d
The array length is e e

char str1[5] = "code";
char str2[5] = "code";
for(i; i < 10; i++)
    {
        printf("The array length is %c %c :\n", str1[i], str2[i]);

    }   

char str1[5] = "code";
char str2[5] = "code";
for(i; i < 10; i++)
    {
        printf("The array length is %s %s :\n", str1[i], str2[i]);

    }   

Recommended Answers

All 4 Replies

Your first example should work if the for loop terminates when i = 5.

char str1[5] = "code";
char str2[5] = "code";

for(i; i < 5; i++)
{
printf("The array length is %c %c :\n", str1[i], str2[i]);
} 

i've doubt in the line below:

for(i; i < 5; i++)

where i is not initialized with value 0. so i think that it should be written as below

for(i=0; i < 5; i++)
    char str1[5] = "code";
    char str2[5] = "code";
    for(i=0; i < 4; i++)
    {
    printf("The array length is %c %c \n", str1[i], str2[i]);
    } 

This gives your expected output.
note : when I did not initialized i = 0,I got a segmentation fault on my system,dont know much about it.
Since it has only 4 letters c o d e you could terminate loop,else you will get blank spaces.

"The array length is %c %c \n

That doesn't print the array length. It prints the character at the ith element in each array. The two are not the same things.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.