Question

Nested loops and numbers pyramid

Asked by: Smanyx

Hi there,

I have a problem trying to generate the pyramid below using nested loops:
----------1
---------232
--------34543
-------4567654
------567898765
-----67890109876
----7890123210987
---890123454321098
--90123456765432109
-0123456789876543210
I need to understand fully how to develop a formula that generates the appropriate output for each line and write the code for it.

So far, my code is not producing this output but rather something different. Here it is anyway, so you can guide me in the right direction:

Thanks.

#include<stdio.h>
#include<stdlib.h>
 
 
 
int main()
 
{     int i,j,k;
     for(i=1; i<=10; i++)
     {
          for (j=1; j<=10-i; j++)
               printf(" ");
          for (k=1; k<=2*i-1; k++)
               printf("%d", k);
               printf("\n");
     }
system("pause");
return 0;
 
 
}

                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-09-19 at 23:51:31ID24746362
Tags

C language

Topic

C Programming Language

Participating Experts
2
Points
50
Comments
25

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Nested if loop
    How do you do a nested if loop in Visual Basic 6? For instace I have if() then else if()then else if()then end if but it's not working, what am I doing wrong?
  2. Nested loops
    Guys, how are you? hope allright. Hey I need some pretty good examples of nested loops in C language. Different kind of examples. Please post some, I'd appreciate it. Peace, The Freebuddy

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: Infinity08Posted on 2009-09-19 at 23:58:34ID: 25376141

Good start

The k loop you have now will have to be split up in two loops. In the pyramid example you posted, on each row, the number first count up towards the middle of the row, and then down again.

So, if you have one loop for counting up, and one for counting back down again, you're all set.

Note also that you'll have to take care not to use 10, but to use 0 instead.

 

by: pgnatyukPosted on 2009-09-20 at 02:22:08ID: 25376406

If it is allowed to "translate" your question...

Actually we have a string "1234567890".
We need to type in each line a string that contains N characters from position i plus the same N characters but in the opposite direction.
In each line we need to increase N and i.
If this is right, I attached a c-file (main.c) that does it. I compiled in VS 2005.

* code removed - assignment *
evilrix EE ZA

                                              
1:
2:

Select allOpen in new window

 

by: Infinity08Posted on 2009-09-20 at 02:34:42ID: 25376434

pgnatyuk, there's no point in posting full code solutions for what is very likely an assignment, but is certainly intended for learning. It's not allowed by this site's rules in fact (and you know that). So, please don't do that.

Smanyx, I suggest to ignore pgnatyuk's reply, and to try to do this yourself with our help. See the hint in my previous post for example.

 

by: pgnatyukPosted on 2009-09-20 at 02:37:26ID: 25376438

Sorry.
Now I think it is really a homework. I hope, I didn't understand the question and my code is wrong.

 

by: SmanyxPosted on 2009-09-20 at 02:37:52ID: 25376439

pgnatyuk:

The output required has to be a isosceles triangle with leading space characters!
And I need to use just nested loops, not advanced concepts such as pointers...
Thanks

Smanyx

 

by: pgnatyukPosted on 2009-09-20 at 02:43:57ID: 25376459

Smanyx, please ignore my post with the code.

 

by: Infinity08Posted on 2009-09-20 at 02:51:58ID: 25376480

Does my hint help you further, Smanyx ?

A good way to start is to try to generate the left half of the pyramid only, ie. :

----------1
---------23
--------345
-------4567
------56789
-----678901
----7890123
---89012345
--901234567
-0123456789

And one that works, you can add the right half.

 

by: SmanyxPosted on 2009-09-20 at 03:03:10ID: 25376511

Infinity08:

I am kind of struggling with the idea of implementing the two loops within the k loop..
I understand that from the top of the triangle to its bottom, that central axis has the following numbers: 1,3,5,7,9.
With this code I get the above output generated twice:
int main()
{
 int i, j, row;
for (i = 1, i <=2, i++)
{
for (j =1, j <=9, j+=2)
{
printf("%d", j);
printf("\n");
row++;
}
}
system("pause");
return 0;

}
This code gives me the following output:
1
3
5
7
9
1
3
5
7
9
Which is kind of the spine of the triangle.
From here, I would like to understand  how I can go about, implementing for each row, the leading space characters and the other digits, counting up and down on each side of the axis and apparently beginning and stopping at the row number.

 

by: pgnatyukPosted on 2009-09-20 at 03:50:56ID: 25376630

I don't know how to continue with this idea.

I think (I can be wrong), you need to think that you have 2 loops where the first handles the position and the count of the characters and the inner loop creates the line to be printed.

Your line is '1234567890'

so, for the first iteration you take the first character - index 0 in the given string and you need to type only 1 character.
For the second iteration you take secon and third characters from the given string - they have indexes 1 and 2.
Then 3 characters - 2, 3 and 4.
And so on.
so the main loop is simple. Right?

Seems like I have to stop here, because people will say that I'm doing your homework. Sorry. Bye.

 

by: SmanyxPosted on 2009-09-20 at 04:13:25ID: 25376719

First of all it's not a homework.

I may be wrong with my last post. I was just a little confused...
I better come back to the first idea then...
I'm still thinking. I will post if I make any progress.

 

by: Infinity08Posted on 2009-09-20 at 04:16:06ID: 25376730

Ok, one step at a time.

You have the outer loop (from your original code) that goes from 1 to 10 :

        for(i=1; i<=10; i++)

Each iteration of this loop corresponds to one row in the pyramid, starting with the top-most.

If we look at the left half of each row, we see that each row starts with the current row number (1 for the first row, 2 for the second row, etc.). And conveniently, we have that row number available in the variable i. The next number on each row is one more than the previous, etc. basically counting, starting from i.

With this information, can you add a second loop inside the above loop that would print the left half of the pyramid ?

 

by: SmanyxPosted on 2009-09-20 at 04:44:59ID: 25376834

No worries evilrix.
I understand.
Thanks.

 

by: SmanyxPosted on 2009-09-21 at 03:20:15ID: 25381491

Hi there,

So far, I have managed to come up with just what seems to be a 'third' of the solution. This is my code:

#include<stdio.h>
#include<stdlib.h>

int main()

{     int i,j,k;

     for(i=0; i<10; i++) //manages the pyramid steps(new lines)
     {
          for (j = 1; j < 10-i; j++)//manages leading space characters
          {
              printf(" ");
               
              }
          for (k=i+1; k<= 2*i+1; k++)//manages what should be written in one line
          {
              printf("%d", k);
          }
         printf("\n");
    }

      system("pause");
    return 0;

}

The output looks partially right, but whenever numbers get greater then 10, how can I, looking at this code, reset that value to 0 and so on...

 

by: Infinity08Posted on 2009-09-21 at 03:26:56ID: 25381520

>> The output looks partially right, but whenever numbers get greater then 10, how can I, looking at this code, reset that value to 0 and so on...

There is a very easy way using the modulo operator (%). The result of (value % 10) is a value between 0 and 9 (inclusive).

 

by: SmanyxPosted on 2009-09-21 at 03:54:03ID: 25381634

Not quite there yet !

Look at what I have, what am I doing wrong?

#include<stdio.h>
#include<stdlib.h>

int main()

{     int i,j,k,m;

     for(i=0; i<10; i++) //manages the pyramid steps(new lines)
     {
          for (j = 1; j < 10-i; j++)//manages leading space characters
          {
              printf(" ");
               
              }
          for (k=i+1; k<= 2*i+1; k++)//manages what should be written in one line
          {
              if (k >= 10)
                    {
                     m = k % 10;
                     printf("%d", m);
                    }
                    else
                    {
                    printf("%d", k);
                    }
          }
              for (k=i+1; k<= 2*i-1; k++)
              {
                    if (k >= 10)
                    {
                     m = k % 10;
                     printf("%d", m);
                    }
                    else
                    {
                    printf("%d", k);
                    }
              }
         printf("\n");
    }

    system("pause");
    return 0;

}

 

by: Infinity08Posted on 2009-09-21 at 04:30:05ID: 25381804

>>               if (k >= 10)
>>                     {
>>                      m = k % 10;
>>                      printf("%d", m);
>>                     }
>>                     else
>>                     {
>>                     printf("%d", k);
>>                     }

You don't have to check whether k is larger than 10. You can simply do :

        printf("%d", k % 10);



>> Look at what I have, what am I doing wrong?

So, the left half of the pyramid is ok. The right half is almost ok, but you're skipping one value. For example, on the third row, you have 3453 instead of 34543.

So you need to adjust the limits to start with the correct value

 

by: Infinity08Posted on 2009-09-21 at 04:52:55ID: 25381916

>> So you need to adjust the limits to start with the correct value

And you'll need to count down instead of up too. The right half of the pyramid has decreasing values.

 

by: SmanyxPosted on 2009-09-21 at 05:24:03ID: 25382148

I am really struggling with the condition the loop for the right half of the pyramid.
I have exausted all possible avenues( I mean from what I believe)... I am now just groping around in the dark. It's may not be rational what I am doing now but, is this any where close?

for (s = k-1; s >= 2*i-1; s--)

k being the last value not written (that stopped the first incrementing loop)
I really need more hints ...

 

by: Infinity08Posted on 2009-09-21 at 05:59:45ID: 25382383

>> for (s = k-1; s >= 2*i-1; s--)

Well, you basically have to do the same thing as the first loop, but in reverse order. So the stop condtion of the second loop is the same as the start condition of the first loop.

 

by: SmanyxPosted on 2009-09-21 at 06:56:42ID: 25382848

I can feel that I'm getting closer but still not quite there yet.
What should I change to this loop ? Is it leading in the right direction?

for (k=2*1+1; k>= i+1; k++)

 

by: Infinity08Posted on 2009-09-21 at 07:02:32ID: 25382902

The upper limit (k>= i+1) is correct.
The increment (k++) is not - remember that we're counting down not up.
The lower limit (k=2*1+1) contains a typo ... I assume that there needed to be an i in there. It is also off by one ...

 

by: SmanyxPosted on 2009-09-21 at 07:13:06ID: 25383008

Bingo !!!!

I got it. I finally got it. This is such a relief !
Infinity08:, thank you so much for your guidance. I really, truly appreciate it.

Here is the final code:

#include<stdio.h>
#include<stdlib.h>
 
int main()
 
{     int i,j,k;
 
     for(i=0; i<10; i++) //manages the pyramid steps(new lines)
     {
          for (j = 1; j < 10-i; j++)//manages leading space characters
          {
              printf(" ");
               
		  }
          for (k=i+1; k<= 2*i+1; k++)//left part of the pyramid, increments
          {
              
			  printf("%d", k % 10); 
			  
          }
			  
		  for (k=2*i; k>= i+1; k--)//right part of the pyramid, decrements
		  {
			  		
			  printf("%d", k % 10 ); 
			
		  }
         printf("\n");
    }
 
	system("pause");
    return 0;
 
}
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:

Select allOpen in new window

 

by: Infinity08Posted on 2009-09-21 at 07:15:17ID: 25383035

That looks good. Short, clean code too :)

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...