You are here:

C++/code for output

Advertisement


Question
i want the code for following outputs
1 1 1  1
2 2  2 2
 3  3 3 3
and also for
4         4
3       3
 2     2
  1   1
    0
  1   1
 2     2
3       3
4         4

Answer
Here are simple functions to print what I believe you are asking for (it is a little unclear in the first one).  Let me know if this is not what you are looking for.

#include <iostream>
using namespace std;

void printShift(int maxVal)
{
   for (int i = 0; i < maxVal; ++i)
   {
       for (int j = 0; j < i; ++j)
         cout << " ";

       for (int j = 0; j < 4; ++j)
         cout << i + 1 << " ";

       cout << endl;
   }
}

void printX(int maxVal)
{
   for (int i = maxVal; i >= -maxVal; --i)
   {
       int numToUse = abs(i);
       for (int j = maxVal - numToUse; j > 0; --j)
         cout << " ";

       cout << numToUse;

       for (int j = 0; j < numToUse + numToUse - 1; ++j)
         cout << " ";

       if (i != 0)
         cout << numToUse;

       cout << endl;
   }
}

int main ()
{
   printShift(3);
   cout << endl;
   printX(4);
}

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Joseph Moore

Expertise

I've been programming in one form or another since my brother taught me BASIC when I was 6. I've been programing professionally since I was 20, first web development with HTML, JS, DHTML, CSS, etc., then I became a video game developer, writing code in C, C++, C#, SQL, assembly, and various scripting languages. I've even written my own scripting languages, custom designed for the games I was making. I also dabble in Java, PHP, and Perl. I've worked on pretty much every aspect of game development, including graphics, audio, gameplay, tool, UI, input, animation, and physics.

Experience

I've been writing C++ code for 12 years, both on my own in my spare time and professionally.

Organizations
IGDA

Education/Credentials
Bachelor of Science in Game Design and Development, Full Sail University, Winter Park, FL

Awards and Honors
Salutatorian and Advanced Achiever Awards at Full Sail; Independent Games Festival Student Showcase winner, 2004; Featured article on Gamasutra about an experimental game developed in 2004

©2016 About.com. All rights reserved.