Table of Contents
Star pattern (using two sets of spaces)
algorithm
Example
Output
Output (n = 10)
Use Grid Method
算法
示例
输出
输出(当n = 8时)
结论
Home Backend Development C++ C++ program to print X star pattern

C++ program to print X star pattern

Sep 13, 2023 am 11:45 AM
c program x star print

C++ program to print X star pattern

Star patterns showing different shapes, such as pyramids, squares and rhombuses, are a

Common parts of basic programming and logic development. we face various problems When we look at loop statements in programming, stars and number patterns are involved. This article demonstrates how to print an X or cross using an asterisk.

We will see the same two methods. The first one is a bit complicated, but the next one The method is very efficient.

Star pattern (using two sets of spaces)

*       *
 *     *
  *   *
   * *
    *
   * *
  *   *
 *     *
*       *
Copy after login

For this pattern, the number of rows is n = 5. This is for the top half. Total X patterns are 2n – 1

Let’s see how to do this using the following table −

The Chinese translation of is: The Chinese translation of is: The translation of is: The translation of is: The Chinese translation of is: The Chinese translation of is: The translation of is: The Chinese translation of is: The Chinese translation of is: The translation of is: The translation of is:
Line numberStar Countnumber of stars remaining spaceSpace Between Spacing describe
11 2 0 7 When i = n, print a star, otherwise print 2. The space on the left is (i – 1), and the space between spaces is 2(n – i) - 1
2 211 5
3 2 2 3
44 2 3 1
551144--
6 2 3 1 The stars on the left are decreasing, such as n - (i - n) - 1 = 2n - i - 1. The number of spaces will follow: 2 * (i - n) - 1
7 2 2 3
8 211 5
99 2 0 7

algorithm

  • Read n as input
  • For the range of i from 1 to 2n - i, execute
    • If i <= n, then
      • For j ranging from 1 to i - 1, execute
        • Show empty space
      • Finish
      • Show stars
      • If i and n are different, then
        • For j ranging from 1 to 2(n - i) - 1, execute
          • Show empty space
        • Finish
        • Show stars
      • If it ends
    • otherwise
      • For j ranging from 1 to 2n - i - 1, execute
        • Show empty space
      • Finish
      • Show stars
      • For j ranging from 1 to 2(i - n) - 1, execute
        • Show empty space
      • Finish
      • Show stars
    • If it ends
    • Move the cursor to the next line
  • Finish

Example

#include <iostream>
using namespace std;
void solve( int n ){
   for ( int i = 1; i <= 2*n - 1; i++ ) {
      if ( i <= n ) {
         for ( int j = 1; j <= i - 1; j++ ) {
            cout << ". ";
         }
         cout << "*  ";
         if ( i != n ) {
            for ( int j = 1; j <= 2 * (n - i) - 1; j++ ) {
               cout << "  ";
            }
            cout << "*  ";
         }
      } else {
         for ( int j = 1; j <= (2 * n) - i - 1; j++ ) {
            cout << ". ";
         }
         cout << "*  ";
         for ( int j = 1; j <= 2 * (i - n) - 1; j++ ) {
            cout << "  ";
         }
         cout << "*  ";
      }
      cout << "\n";
   }
}
int main(){
   int n = 8;
   cout << "X Star Pattern for " << n << " lines." << endl;
   solve( n );
}
Copy after login

Output

X Star Pattern for 8 lines.
*                            *  
. *                        *  
. . *                    *  
. . . *                *  
. . . . *            *  
. . . . . *        *  
. . . . . . *    *  
. . . . . . . *  
. . . . . . *    *  
. . . . . *        *  
. . . . *            *  
. . . *                *  
. . *                    *  
. *                        *  
*                            *
Copy after login

Output (n = 10)

X Star Pattern for 10 lines.
*                                    *  
. *                                *  
. . *                            *  
. . . *                        *  
. . . . *                    *  
. . . . . *                *  
. . . . . . *            *  
. . . . . . . *        *  
. . . . . . . . *    *  
. . . . . . . . . *  
. . . . . . . . *    *  
. . . . . . . *        *  
. . . . . . *            *  
. . . . . *                *  
. . . . *                    *  
. . . *                        *  
. . *                            *  
. *                                *  
*                                    *  
Copy after login

Use Grid Method

The same problem can be solved by considering a grid, and from this grid, we can calculate The formula where the stars are printed and where the spaces are printed.

* *
* *
* *
* *
*
* *
* *
* *
* *

从上面的网格中,很容易理解,星星只会在列中放置 数字与行号(对角线)相同,列号为 (2n + 1 – i)

算法

  • 读取 n 作为输入
  • m = 2n - i
  • 对于从 1 到 m 的 i,执行
    • 对于 j 从 1 到 m 的范围,执行
      • 如果 j 与 i 相同或 j 与 (m + 1) - i 相同,则执行
        • 显示星星
      • 否则
        • 显示空间
      • 如果结束
    • 结束
    • 将光标移至下一行
  • 结束

示例

#include <iostream>
using namespace std;
void solve( int n ){
   int m = 2*n - 1;
   for ( int i = 1; i <= m; i++ ) {
      for ( int j = 1; j <= m; j++ ) {
         if (j == i || j == (m + 1 - i))
            cout << "* ";
         else
            cout << ". ";
      }
      cout << endl;
   }
}
int main(){
   int n = 6;
   cout << "X Star Pattern for " << n << " lines." << endl;
   solve( n );
}
Copy after login

输出

X Star Pattern for 6 lines.
* . . . . . . . . . * 
. * . . . . . . . * . 
. . * . . . . . * . . 
. . . * . . . * . . . 
. . . . * . * . . . . 
. . . . . * . . . . . 
. . . . * . * . . . . 
. . . * . . . * . . . 
. . * . . . . . * . . 
. * . . . . . . . * . 
* . . . . . . . . . * 
Copy after login

输出(当n = 8时)

X Star Pattern for 8 lines.
* . . . . . . . . . . . . . * 
. * . . . . . . . . . . . * . 
. . * . . . . . . . . . * . . 
. . . * . . . . . . . * . . . 
. . . . * . . . . . * . . . . 
. . . . . * . . . * . . . . . 
. . . . . . * . * . . . . . . 
. . . . . . . * . . . . . . . 
. . . . . . * . * . . . . . . 
. . . . . * . . . * . . . . . 
. . . . * . . . . . * . . . . 
. . . * . . . . . . . * . . . 
. . * . . . . . . . . . * . . 
. * . . . . . . . . . . . * . 
* . . . . . . . . . . . . . * 
Copy after login

结论

星形模式使用简单,对于学习编程循环思想很有用。这 文章演示了如何使用 C++ 显示左和右半菱形图案 右对齐的半菱形。拍摄后,X 或十字图案将使用星号显示 考虑n行计数。为此,我们提供了两种方法。一聘 填充和空白空间,而另一个则利用网格计算。而不是添加 空格,我们添加了点。如果没有,他们偶尔会从输出中删除空格。

The above is the detailed content of C++ program to print X star pattern. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

C language data structure: data representation and operation of trees and graphs C language data structure: data representation and operation of trees and graphs Apr 04, 2025 am 11:18 AM

C language data structure: The data representation of the tree and graph is a hierarchical data structure consisting of nodes. Each node contains a data element and a pointer to its child nodes. The binary tree is a special type of tree. Each node has at most two child nodes. The data represents structTreeNode{intdata;structTreeNode*left;structTreeNode*right;}; Operation creates a tree traversal tree (predecision, in-order, and later order) search tree insertion node deletes node graph is a collection of data structures, where elements are vertices, and they can be connected together through edges with right or unrighted data representing neighbors.

The truth behind the C language file operation problem The truth behind the C language file operation problem Apr 04, 2025 am 11:24 AM

The truth about file operation problems: file opening failed: insufficient permissions, wrong paths, and file occupied. Data writing failed: the buffer is full, the file is not writable, and the disk space is insufficient. Other FAQs: slow file traversal, incorrect text file encoding, and binary file reading errors.

How do I use rvalue references effectively in C  ? How do I use rvalue references effectively in C ? Mar 18, 2025 pm 03:29 PM

Article discusses effective use of rvalue references in C for move semantics, perfect forwarding, and resource management, highlighting best practices and performance improvements.(159 characters)

How to calculate c-subscript 3 subscript 5 c-subscript 3 subscript 5 algorithm tutorial How to calculate c-subscript 3 subscript 5 c-subscript 3 subscript 5 algorithm tutorial Apr 03, 2025 pm 10:33 PM

The calculation of C35 is essentially combinatorial mathematics, representing the number of combinations selected from 3 of 5 elements. The calculation formula is C53 = 5! / (3! * 2!), which can be directly calculated by loops to improve efficiency and avoid overflow. In addition, understanding the nature of combinations and mastering efficient calculation methods is crucial to solving many problems in the fields of probability statistics, cryptography, algorithm design, etc.

How do I use move semantics in C   to improve performance? How do I use move semantics in C to improve performance? Mar 18, 2025 pm 03:27 PM

The article discusses using move semantics in C to enhance performance by avoiding unnecessary copying. It covers implementing move constructors and assignment operators, using std::move, and identifies key scenarios and pitfalls for effective appl

What are the basic requirements for c language functions What are the basic requirements for c language functions Apr 03, 2025 pm 10:06 PM

C language functions are the basis for code modularization and program building. They consist of declarations (function headers) and definitions (function bodies). C language uses values ​​to pass parameters by default, but external variables can also be modified using address pass. Functions can have or have no return value, and the return value type must be consistent with the declaration. Function naming should be clear and easy to understand, using camel or underscore nomenclature. Follow the single responsibility principle and keep the function simplicity to improve maintainability and readability.

Function name definition in c language Function name definition in c language Apr 03, 2025 pm 10:03 PM

The C language function name definition includes: return value type, function name, parameter list and function body. Function names should be clear, concise and unified in style to avoid conflicts with keywords. Function names have scopes and can be used after declaration. Function pointers allow functions to be passed or assigned as arguments. Common errors include naming conflicts, mismatch of parameter types, and undeclared functions. Performance optimization focuses on function design and implementation, while clear and easy-to-read code is crucial.

Concept of c language function Concept of c language function Apr 03, 2025 pm 10:09 PM

C language functions are reusable code blocks. They receive input, perform operations, and return results, which modularly improves reusability and reduces complexity. The internal mechanism of the function includes parameter passing, function execution, and return values. The entire process involves optimization such as function inline. A good function is written following the principle of single responsibility, small number of parameters, naming specifications, and error handling. Pointers combined with functions can achieve more powerful functions, such as modifying external variable values. Function pointers pass functions as parameters or store addresses, and are used to implement dynamic calls to functions. Understanding function features and techniques is the key to writing efficient, maintainable, and easy to understand C programs.

See all articles