0

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 .

14
  • you need to include a newline character - printf("%c\n", aaa[i]); also, it is a good idea to get into the habit of calling variables, such as arrays, something that describes their purpose. 'aaa' isn't self-describing. Commented May 3, 2017 at 8:47
  • Replace with printf("%c " , aaa[i] ) ; It will add space between array elements and If you need newline use printf("%c \n" , aaa[i] ) ; Commented May 3, 2017 at 8:49
  • 2
    what is your expected output ?? Commented May 3, 2017 at 8:59
  • 1
    @Mohammad do you want the strings aaa[0], aaa[4] also to be printed? Can you just show the sample output? Commented May 3, 2017 at 9:05
  • 2
    @Mohammed, is your desired output like: "#ell# Wo#ld!#"? Commented May 3, 2017 at 9:11

2 Answers 2

4

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 printfing 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);
Sign up to request clarification or add additional context in comments.

Comments

3

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++;
}

1 Comment

Thank you . Yes I wanted this . or something like this . Thank you all ! But there is another tiny problem . I want to clear aaa[0] when I'm printing aaa[4] . But when I use system("cls") , everything start from beginning .what can I do? It's you kindness to help me with this .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.