0

I need an output, in which the string will be divided in pair of two letters. As example I put this code bellow, but it prints M O N A R C H Y, and what I need is: MO NA RC HY

char arr[8] = "MONARCHY"; 

int n = 8;
    
for (int i = 0; i < n; i++) {
    printf("%*c", 1 + !!i, arr[i]);
}
0

4 Answers 4

2

This is the smallest code change I could figure out:

#include <stdio.h>

int main(void) {
    char arr[] = "MONARCHY"; 
    int n = strlen(arr);
    
    for (int i = 0; i < n; i++) 
    {
        printf("%-*c", 1 + i%2, arr[i]);
    }
    return 0;
}

Output

Success #stdin #stdout 0s 4208KB
MO NA RC HY 
1

This code should work:

char arr[8] = "MONARCHY";

int n = 8;

for (int i = 0; i < n; i=i+2) {

    printf("%c%c ", arr[i], arr[i+1]);

}
0
1

Yet another simple solution:

#include <stdio.h>
#include <string.h>

int main(void) {
    char arr[] = "MONARCHY";
    int n = strlen(arr);

    printf("%.2s", arr);
    for (int i = 2; i < n; i += 2)
        printf(" %.2s", arr + i);

    return 0;
}
0

You can try the following

char arr[8] = "MONARCHY";

int n = 8;

for (int i = 0; i < n; i++) {
    if (i + 1 < n ) {
        printf("%c%c ", arr[i],arr[i+1]);
        i++;
    } 
    else {
        printf("%c", arr[i]);
    }
}
1
  • Not a good idea to use hardcoded value of n. It's better to run the loop till you don't find '\0'
    – Tushar
    Commented Nov 29, 2020 at 0:35