I have been stumped by this problem. I need to create a pattern such as:
1
21
221
2221
22221
Using nested for loops. I have something that does (A)
222221
222221
222221
222221
222221
and used to have something that did (B)
/* 1
* 21
* 221
* 2221
* 22221
* 222221
* 2222222
*/
#include <stdio.h>
main()
{
int n, c, k;
printf("Enter number of rows\n");
scanf("%d",&n);
for ( c = 1 ; c <= n ; c++ )
{
printf("1\n");
for( k = 1 ; k <= c ; k++ )
printf("2");
}
return 0;
}
Any hints would be helpful.
Solution – Thanks to the intelligent people that decided to help.
I appreciate your help!
#include <stdio.h>
main()
{
int n, c, k;
printf("Enter number of rows");
scanf("%d",&n);
for ( c = 1 ; c <= n ; c++ )
{
for( k = 1 ; k < c ; k++ )
{
printf("2");
}
printf("1\n");
}
return 0;
}
This can be done using nested for loops. Let’s examine the formulae for one line of the output:
line 1:
Which can be made using a simple for loop like this:
line 2:
Hmm, this requires change to our structure, as we can’t break the output of iteration #1, but we still need to be able to add the ‘2’ in there… Something like this should work:
line 3:
Wait, now we need two ‘2’s in there! How can we do this without breaking line’s 2 and three? Well something like this should do it:
Notice that I used a
whileloop instead of a for loop. It is an exercise to the reader to figure out how to turn that while loop into a for loop.Hopefully this helped you to understand the process behind solving similar problems like this in the future – as it is an important programming skill to have.