TransWikia.com

How to print diagonal star pattern in C

Stack Overflow Asked by Amrit Singh on February 27, 2021

I’m confused to print this type of pattern given below:

 *   *
  * * 
   *  
  * * 
 *   * 

I’ve tried this:

#include <stdio.h>

int main()
{
    int n; 
    printf("Enter the value of basen>>> ");
    scanf("%d", &n);

    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j + n; j++)
        {
            if (// ??? )
            {
                printf("*");
            }
            
            else
            {
                printf(" ");
            }
            
        }

        printf("n");
    }

    return 0;
}

but I don’t know what is the condition of if statement
Help Me to solve this please

3 Answers

This will work fine !! :)

#include<iostream>
using namespace std;


int main()
{
    int n,m=0;
    int m2=0;
    cin>>n;
    int f=-1,l=n;
    for(int i=0;i<n;i++)
    {
        f=f+1;
        l=l-1;
        
        for(int j=0;j<n;j++)
        {
            if(j==f || j==l) cout<<"*";
            else cout<<" ";
        }
        
        cout<<endl;
    }
}

Answered by Aniket Verma on February 27, 2021

To not change any code and answer your question "what goes in the if"

n - 1 - i == j || j == i

this does

Answered by FuzzyNovaGoblin on February 27, 2021

The pattern consists of exactly n * 2 - 1 rows and columns. So you can run an outer loop to iterate through rows with structure for(i=1; i<= count; i++); where count = n * 2 - 1. Each row contains exactly n * 2 - 1 columns. So, run inner loop as for(j=1; j<=count; j++). And inside this loop we need stars to be printed when row and column number both are equal (i.e. print star whenever if(i == j)) and if(j == count - i + 1). For example:

#include <stdio.h>

int main() {
  int i, j, n;
  int count;

  printf("Enter n: ");
  scanf("%d", &n);

  count = n * 2 - 1;

  for (i = 1; i <= count; i++) {
    for (j = 1; j <= count; j++) {
      if (j == i || (j == count - i + 1)) {
        printf("*");
      } else {
        printf(" ");
      }
    }

    printf("n");
  }

  return 0;
}

Answered by 1218985 on February 27, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP