Write a program to produce the following output using nested

Write a program to produce the following output using nested for loops. Use a table to help you figure out the patterns of character on each line. Test your loop expressions in Practice-It! using the checkmark icon above. Use your expressions in the loop tests of the inner loops of your code.

Solution

Pseudo Algorithm/Logic for writing the program .

1) Observe that every line has exactly 11 characters.

2) On every line, the number of times a digit has been printed = the value of the digit. Hence, 1 is printed once, 3 is printed thrice and so on. Also, only odd digits are printed.

3) The digits are placed in the centre. This means that the dashes on either side are equal. It therefore follows that , the number of dashes on either side = (total_characters - digit)/2

We use the above three points to formulate our solution. We make use of nested loops as follows :

1) Outer loop that takes care of the line number.

2) Inner loop or loops that print the required number of dashes and digits on each line.

The following code implements the logic above :

#include<stdio.h>

int main()
{

int total_characters_in_line = 11;
int digit;
int digit_print_count;
int total_dashes;
int dashes_on_either_side;
//counters
int i=0;
int j=0;

//outer loop . Each iteration prints one line.

for(i=0;i<5;i++)
{

//finding the digit to be printed.
digit = (i*2)+1;
digit_print_count = digit;

total_dashes = total_characters_in_line - digit_print_count;
dashes_on_either_side = total_dashes/2;

//printing the dashes before the digits.

for (j=0;j<dashes_on_either_side;j++)
{
printf(\"-\");

}

//printing the digits

for (j=digit_print_count; j>0; j--)
{
printf(\"%d\",digit);
}

//printing the dashes after the digit

for (j=0;j<dashes_on_either_side;j++)
{
printf(\"-\");
}

//the pattern has been printed . We move to the next line .

printf(\"\ \");

}

}








 Write a program to produce the following output using nested for loops. Use a table to help you figure out the patterns of character on each line. Test your lo
 Write a program to produce the following output using nested for loops. Use a table to help you figure out the patterns of character on each line. Test your lo

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site