search
HomeBackend DevelopmentC++C++ program to print spiral pattern of numbers

C++ program to print spiral pattern of numbers

Displaying numbers in different formats is one of the problems of learning basic coding.

Different coding concepts like conditional statements and loop statements. have In different programs we use special characters like asterisks to print triangles or square. In this article, we will print numbers in a spiral, just like the squares in C.

We take the number of rows n as input, and then start from the upper left corner Move to the right, then down, then left, then up, then right again, and so on etc.

Spiral pattern and numbers

1   2   3   4   5   6   7
24  25  26  27  28  29  8
23  40  41  42  43  30  9
22  39  48  49  44  31  10
21  38  47  46  45  32  11
20  37  36  35  34  33  12
19  18  17  16  15  14  13

To solve this problem, we will use a two-dimensional matrix of size n x n, in this case, we take n = 7. Then fill the matrix in a spiral starting from the upper left corner. final printout the entire matrix. Here we are printing from 1 to 7 on the first line and then the process is changing it's direction, move toward the bottom to 13, then to the left to 19, and finally Go up until 24, then right, and so on. Let's look at a better algorithm understand.

algorithm

  • Enter s as the number of lines
  • Create a s x s matrix and initialize them with 0
  • Number: = 1
  • Initialize i, j, m to 0
  • Initialize n := s - 1, p := 0 and q := s - 1
  • When num does not exceed s * s, execute
    • For the range of j from p to q, execute
      • mat[ m, j ] := num
      • Number := Number 1
  • Finish
  • meter:=meter 1
  • For i from m to n, execute
    • mat[ i, q ] := num
    • Number := Number 1
  • Finish
  • q := q - 1
  • For the range of j from q to p, decrease it by 1 each time and execute
    • mat[ n, j ] := num
    • Number := Number 1
  • Finish
  • n := n - 1
  • For i from n to m, decrease i by 1 and execute
    • mat[ i, p ] := num
    • Number := Number 1
  • Finish
  • p := p 1
  • Finish
  • For i from 0 to s-1, perform the following operations
    • For j ranging from 0 to s - 1, execute
      • Display mat[ i, j ]
    • Finish
    • Move the cursor to the next line
  • Finish
  • The Chinese translation of

    Example

    is:

    Example

    #include <iostream>
    using namespace std;
    void solve( int s ){
       int mat[ s ][ s ] = {0};
       int i, j, m, n, p, q, num;
       num = 1; // start count from 1
       i = 0;
       j = 0;
       m = 0; // row index lower limit
       n = s - 1; // row index upper limit
       p = 0; // column index lower limit
       q = s - 1; // column index upper limit
       while ( num <= s * s ) {
       
          // place numbers horizontally left to right
          for ( j = p; j <= q; j++ ) {
             mat[ m ][ j ] = num;
             num = num + 1;
          }
          m = m + 1;
       
          // fill vertically from top to bottom
          for ( i = m; i <= n; i++ ) {
             mat[ i ][ q ] = num;
             num = num + 1;
          }
          q = q - 1;
    
          // fill horizontally from right to left
          for ( j = q; j >= p; j-- ) {
             mat[ n ][ j ] = num;
             num = num + 1;
          }
          n = n - 1;
    
          // fill vertically from bottom to top
          for ( i = n; i >= m; i-- ) {
             mat[ i ][ p ] = num;
             num++;
          }
          p = p + 1;
       }
    
       // display the mat
       for ( i = 0; i < s; i++ ) {
          for ( j = 0; j < s; j++ ) {
             printf("%d\t", mat[i][j]);
          }
          printf("\n");
       }
    }
    int main(){
       int n = 5;
       cout << "Spiral numbers for " << n << " lines." << endl;
       solve( n );
    }
    

    Output

    Spiral numbers for 5 lines.
    1	2	3	4	5	
    16	17	18	19	6	
    15	24	25	20	7	
    14	23	22	21	8	
    13	12	11	10	9
    

    Output results (when n = 12)

    Spiral numbers for 12 lines.
    1	2	3	4	5	6	7	8	9	10	11	12	
    44	45	46	47	48	49	50	51	52	53	54	13	
    43	80	81	82	83	84	85	86	87	88	55	14	
    42	79	108	109	110	111	112	113	114	89	56	15	
    41	78	107	128	129	130	131	132	115	90	57	16	
    40	77	106	127	140	141	142	133	116	91	58	17	
    39	76	105	126	139	144	143	134	117	92	59	18	
    38	75	104	125	138	137	136	135	118	93	60	19	
    37	74	103	124	123	122	121	120	119	94	61	20	
    36	73	102	101	100	99	98	97	96	95	62	21	
    35	72	71	70	69	68	67	66	65	64	63	22	
    34	33	32	31	30	29	28	27	26	25	24	23
    

    in conclusion

    Displaying number patterns is a fairly common problem when learning programming language. In this article we learned how to display numbers in the square in which the element is located Print in a spiral form in C, starting from the top left corner and moving downwards At the end of column n, we move down, then at the end of row n, we move left, then After reaching the first row, move up until row 2nd, then repeat this process over and over again until... Complete the entire square. Unlike other numeric pattern problems, it requires a 2D array Solve this problem effectively.

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

    Statement
    This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
    C# vs. C  : Learning Curves and Developer ExperienceC# vs. C : Learning Curves and Developer ExperienceApr 18, 2025 am 12:13 AM

    There are significant differences in the learning curves of C# and C and developer experience. 1) The learning curve of C# is relatively flat and is suitable for rapid development and enterprise-level applications. 2) The learning curve of C is steep and is suitable for high-performance and low-level control scenarios.

    C# vs. C  : Object-Oriented Programming and FeaturesC# vs. C : Object-Oriented Programming and FeaturesApr 17, 2025 am 12:02 AM

    There are significant differences in how C# and C implement and features in object-oriented programming (OOP). 1) The class definition and syntax of C# are more concise and support advanced features such as LINQ. 2) C provides finer granular control, suitable for system programming and high performance needs. Both have their own advantages, and the choice should be based on the specific application scenario.

    From XML to C  : Data Transformation and ManipulationFrom XML to C : Data Transformation and ManipulationApr 16, 2025 am 12:08 AM

    Converting from XML to C and performing data operations can be achieved through the following steps: 1) parsing XML files using tinyxml2 library, 2) mapping data into C's data structure, 3) using C standard library such as std::vector for data operations. Through these steps, data converted from XML can be processed and manipulated efficiently.

    C# vs. C  : Memory Management and Garbage CollectionC# vs. C : Memory Management and Garbage CollectionApr 15, 2025 am 12:16 AM

    C# uses automatic garbage collection mechanism, while C uses manual memory management. 1. C#'s garbage collector automatically manages memory to reduce the risk of memory leakage, but may lead to performance degradation. 2.C provides flexible memory control, suitable for applications that require fine management, but should be handled with caution to avoid memory leakage.

    Beyond the Hype: Assessing the Relevance of C   TodayBeyond the Hype: Assessing the Relevance of C TodayApr 14, 2025 am 12:01 AM

    C still has important relevance in modern programming. 1) High performance and direct hardware operation capabilities make it the first choice in the fields of game development, embedded systems and high-performance computing. 2) Rich programming paradigms and modern features such as smart pointers and template programming enhance its flexibility and efficiency. Although the learning curve is steep, its powerful capabilities make it still important in today's programming ecosystem.

    The C   Community: Resources, Support, and DevelopmentThe C Community: Resources, Support, and DevelopmentApr 13, 2025 am 12:01 AM

    C Learners and developers can get resources and support from StackOverflow, Reddit's r/cpp community, Coursera and edX courses, open source projects on GitHub, professional consulting services, and CppCon. 1. StackOverflow provides answers to technical questions; 2. Reddit's r/cpp community shares the latest news; 3. Coursera and edX provide formal C courses; 4. Open source projects on GitHub such as LLVM and Boost improve skills; 5. Professional consulting services such as JetBrains and Perforce provide technical support; 6. CppCon and other conferences help careers

    C# vs. C  : Where Each Language ExcelsC# vs. C : Where Each Language ExcelsApr 12, 2025 am 12:08 AM

    C# is suitable for projects that require high development efficiency and cross-platform support, while C is suitable for applications that require high performance and underlying control. 1) C# simplifies development, provides garbage collection and rich class libraries, suitable for enterprise-level applications. 2)C allows direct memory operation, suitable for game development and high-performance computing.

    The Continued Use of C  : Reasons for Its EnduranceThe Continued Use of C : Reasons for Its EnduranceApr 11, 2025 am 12:02 AM

    C Reasons for continuous use include its high performance, wide application and evolving characteristics. 1) High-efficiency performance: C performs excellently in system programming and high-performance computing by directly manipulating memory and hardware. 2) Widely used: shine in the fields of game development, embedded systems, etc. 3) Continuous evolution: Since its release in 1983, C has continued to add new features to maintain its competitiveness.

    See all articles

    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 agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    1 months agoBy尊渡假赌尊渡假赌尊渡假赌
    Will R.E.P.O. Have Crossplay?
    1 months agoBy尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    MinGW - Minimalist GNU for Windows

    MinGW - Minimalist GNU for Windows

    This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

    PhpStorm Mac version

    PhpStorm Mac version

    The latest (2018.2.1) professional PHP integrated development tool

    DVWA

    DVWA

    Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

    Safe Exam Browser

    Safe Exam Browser

    Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

    VSCode Windows 64-bit Download

    VSCode Windows 64-bit Download

    A free and powerful IDE editor launched by Microsoft