Michael Ji
Michael Ji

Reputation: 167

How do I print a string's characters in a diagonal pattern?

I am trying to write a program that reads a string from the user and prints the string's characters in a diagonal pattern. I set the maximum length of the string as 50 characters. The program can print the characters in a diagonal pattern, but it doesn't print the characters correctly.

#include<stdio.h>

int main () {
  int i = 0, j = 0, m;
  char c[50];

  printf("Enter a string: ");
  scanf("%c", c);

  m = sizeof(c) / sizeof(c[0]);

  for (i = 1; i <= m; i++) {
    for (j = 1; j <= i; j++) {
      if (j == i) {
        printf("%c", c[i-1]);
      } else {
        printf(" ");
      }
    }
    printf("\n");
  }
  return 0;
}

Upvotes: 0

Views: 7828

Answers (1)

Gopi
Gopi

Reputation: 19874

Check the code below:

#include<stdio.h>
int main ()
{
    int i=0,s=0;
    char c[50];
    printf("Enter a string: ");
    scanf("%s",c);

    while(c[i] != '\0')
        {
            s = i;
            while(s--)
            printf(" ");
            printf("%c\n",c[i]);
             i++; 
        }
        return 0;
}

Upvotes: 1

Related Questions