user14632510
user14632510

Reputation:

Printf a string (in C)

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]);
}

Upvotes: 0

Views: 401

Answers (4)

chqrlie
chqrlie

Reputation: 144695

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

Upvotes: 1

abelenky
abelenky

Reputation: 64682

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 

Upvotes: 2

qwertyuiop
qwertyuiop

Reputation: 11

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]);

}

Upvotes: 1

Mod
Mod

Reputation: 1

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]);
    }
}

Upvotes: 0

Related Questions