-
Reducing loops
Hello,
I got folllowing code working but need to work on optimization.
Can anybidy help me in reducing number of loops?
main()
{
int height,i,j,k;
while ( getch() == 'c' )
{
printf("Enter the height of triangle\n");
scanf("%d",&height);
printf("Height = %d\n",height);
k = 1;
for ( i = 0; i < height; i++)
{
j = height-i-1;
while ( j--)
putch(' ');
for ( j = 0; j < k ; j++)
putch('*');
printf("\n");
k = k+2;
}
k = 1;
for ( i = 0; i < height; i++)
{
j = i;
while ( j--)
putch(' ');
for ( k = (((height-i)*2)-1); k ; k--)
putch('*');
printf("\n");
k = k-2;
}
printf("\n\n\n Press 'c' to continue\n");
}
}
-
Please read this then edit your post accordingly.
-
here you go
Code:
main()
{
int height,i,j,k;
while ( getch() == 'c' )
{
printf("Enter the height of triangle\n");
scanf("%d",&height);
printf("Height = %d\n",height);
k = 1;
for ( i = 0; i < height; i++)
{
j = height-i-1;
while ( j--)
putch(' ');
for ( j = 0; j < k ; j++)
putch('*');
printf("\n");
k = k+2;
}
k = 1;
for ( i = 0; i < height; i++)
{
j = i;
while ( j--)
putch(' ');
for ( k = (((height-i)*2)-1); k ; k--)
//for ( j = k ; j ; j--)
putch('*');
printf("\n");
k = k-2;
}
printf("\n\n\n Press 'c' to continue\n");
}
}
-
Here's the first for loop rewritten to not use internal loops. See what you make of it and if you can apply its logic to the second loop.
Code:
for ( i = 0, k = 1; i < height; i++, k += 2)
{
j = height-i-1;
printf ("%*.s", j, " ");
/* This next line limits the height of the triangle based on the
* number of *'s in the string.
* Therefore, it is not as flexible as a loop
*/
printf ("%.*s", k, "****************************************");
putchar('\n');
}
-
Here's an idea:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main( void )
{
char *line = NULL;
int linesize, size, front, back;
printf("Enter the size of the pyramid: ");
if( scanf("%d",&size) != 1 )
{
printf("You suck, go away.\n");
exit( 0 );
}
linesize = size * 2 + 1;
if( (line = malloc( sizeof( char ) * linesize )) == NULL )
{
printf("Your computer sucks, go away.\n");
exit( 0 );
}
memset( line, ' ', linesize );
line[linesize-1] = '\0';
for( front = back = size; size > 0; size--, front--, back++)
{
line[back] = line[front] = '*';
printf("%s\n", line );
}
free( line );
getchar( );
return 0;
}
Don't turn this in for homework please. I figured it's be an amusing work around. Enjoy.
[edit]You don't actually need the 'front' line here. You could just use size.[/edit]
Quzah.