Thread: Looking for a better code

  1. #1
    Registered User
    Join Date
    May 2009
    Posts
    7

    Looking for a better code

    OUTPUT display should be:

    0 1 2 3
    4 5 6
    7 8
    9


    Code:
    int x=0;
    
    for(x=0;x<=9;x++)
    {
      printf("%d",x);
      if(x==3||x==6||x==8)
       {
       printf("\n");
       }
    }
    is there any way that i can print new line without using the if statement?
    or can i have the same output using only loops.. thats my solution with if's i can't get it only with loops.
    or maybe im on the right track?
    Last edited by nhoda911; 05-12-2009 at 03:26 AM.

  2. #2
    Complete Beginner
    Join Date
    Feb 2009
    Posts
    312
    Quote Originally Posted by nhoda911 View Post
    is there any way that i can print new line without using the if statement?
    or can i have the same output using only loops.. thats my solution with if's i can't get it only with loops.
    or maybe im on the right track?
    There's a nice solution for arbitrary triangles which only uses two loops. Here's a hint: let the outer loop count from 0 to <length of first row> - 1. The inner loop starts at 0; where does it stop? Use a second variable for storing/incrementing the output value.

    Greets,
    Philip
    All things begin as source code.
    Source code begins with an empty file.
    -- Tao Te Chip

  3. #3
    Registered User
    Join Date
    May 2009
    Posts
    7
    wew i got it!!! thanks for the tip!
    here's my final code:
    Code:
    #include<stdio.h>
    #include<conio.h>
    int main()
    {
    clrscr();
    int x=4,y=0,z=0;
    
    for(x=4;x>=1;x--)
    {
    	for(y=1;y<=x;y++)
    	{
    	printf("%d",z);
    	z++;
    	}printf("\n");
    }
    
    getch();
    return 0;
    }
    is this right? my output is already correct! thanks again.... weew

  4. #4
    Complete Beginner
    Join Date
    Feb 2009
    Posts
    312
    Quote Originally Posted by nhoda911 View Post
    is this right? my output is already correct! thanks again.... weew
    That's roughly what I had in mind. Good job :-)

    Greets,
    Philip
    All things begin as source code.
    Source code begins with an empty file.
    -- Tao Te Chip

  5. #5
    Registered User
    Join Date
    May 2009
    Posts
    7
    thanks again mr. snafuist!!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Extended ASCII Characters in an RTF Control
    By JustMax in forum C Programming
    Replies: 18
    Last Post: 04-03-2009, 08:20 PM
  2. Enforcing Machine Code Restrictions?
    By SMurf in forum Tech Board
    Replies: 21
    Last Post: 03-30-2009, 07:34 AM
  3. Values changing without reason?
    By subtled in forum C Programming
    Replies: 2
    Last Post: 04-19-2007, 10:20 AM
  4. Interface Question
    By smog890 in forum C Programming
    Replies: 11
    Last Post: 06-03-2002, 05:06 PM
  5. Replies: 0
    Last Post: 02-21-2002, 06:05 PM