Reputation: 27
I am a newbie to C and want to print some special elements of an array.
//Partial code here
char aaa[18] ;
int i = 0;
while(i < 18) {
aaa[i] = '#' ;
printf("%c", aaa[i]) ;
i = i + 4 ;
}
It's supposed to prints 4 #
of aaa[0] ,aaa[4],aaa[8],aaa[12],aaa[16]. But it is not. It is printing them in a row like #####
. But I don't want those .
Upvotes: 0
Views: 374
Reputation:
I'm assuming you want to eventually print a string and get output like this
"# # # # # "
minus the quotes.
You can do this by filling in a null-terminated string and then printf
ing that, like so:
// +1 for space for a null terminator
// = {0}; fills the array with 0s
char aaa[18+1] = {0};
// for loop is more idiomatic for looping over an array of known size
for (int i = 0; i < 18; i += 4) {
// if the remainder of dividing i by 4 is equal to 0
if (i % 4 == 0) {
// then put a '#' character in the array at aaa[i]
aaa[i] = '#';
} else {
// otherwise put a ' ' character in the array at aaa[i]
aaa[i] = ' ';
}
}
printf("%s", aaa);
Upvotes: 4
Reputation: 169
As you're adding 4 to the i variable in each cycle you're printing the positions 0, 4, 8, 12, 16 of the array consecutively.
If you want to print the vector with # as the 4*nth element you should do something like:
while( i < 18 )
{
if( i % 4 == 0 )
{
aaa[i] = '#';
printf("%c" ,aaa[i]);
}
else
printf(" "); // Assuming you want a space in between prints
i++;
}
Upvotes: 3