patternprogram_200 softethics

Pattern 200 (Binary No.Pattern)

C

#include <stdio.h>
long toBinary(int n);

int main()
{
  int n = 3, x = 1;
  int i,j;

  for(i = 1; i <= n; i++)
  {
    for (j = 1; j <= n; j++)
    {
      printf("%4d ",toBinary(x));
      x++;
    }
    printf("\n");
  }
  return 0;
}

long toBinary(int n)
{
  long bin = 0;
  int rem, i = 1, step = 1;
  while (n != 0)
  {
    rem = n % 2;
    n /= 2;
    bin += rem * i;
    i *= 10;
  }
  return bin;
}

C++

#include <iostream.h>
#include <iomanip.h>

long toBinary(int n);

int main()
{
  int n = 3, x = 1;
  
  for(int i = 1; i <= n; i++)
  {
    for(int j = 1; j <= n; j++)
    {
      cout<<setw(5)<<toBinary(x);
      x++;
    }
    cout<<endl;
  }
  return 0;
}

long toBinary(int n)
{
   long bin = 0;
   int rem, i = 1, step = 1;
   while (n != 0)
   {
    rem = n % 2;
    n /= 2;
    bin += rem * i;
    i *= 10;
    }
    return bin;
}

Java

class PatternProg
{


	public static void main(String args[])
	{
	  int n = 3;
	  int x = 1;

	  for (int i = 1; i <= n; i++)
	  {
		for (int j = 1; j <= n; j++)
		{
		  System.out.printf("%5s", Integer.toBinaryString(x));
		  x++;
		}
		System.out.println();
	  }
	  
	}
	
	/*
	 *To determine binary  via user-defined method
	 *
	public static int toBinary(int n)
	{
	   int bin = 0;
	   int rem;
	   int i = 1;
	   int step = 1;
	   while (n != 0)
	   {
		rem = n % 2;
		n /= 2;
		bin += rem * i;
		i *= 10;
	   }
		return bin;
	}
	*/
}

C#

using System;

class PatternProg
{
  public static void Main()
  {
    int n = 3;
    int x = 1;

    for (int i = 1; i <= n; i++)
    {
      for (int j = 1; j <= n; j++)
      {
        Console.Write("{0,5:D}", Convert.ToString(x, 2));
        x++;
      }
      Console.WriteLine("     "); // 5ws
    }

    Console.ReadKey(true);
  }


  /*
  *To determine binary  via user-defined method
  *
  public static int toBinary(int n)
  {
  int bin = 0;
  int rem;
  int i = 1;
  int step = 1;
  while (n != 0)
  {
  rem = n % 2;
  n /= 2;
  bin += rem * i;
  i *= 10;
  }
  return bin;
  }
  */
}

Python

n = 3
d = 1

for x in range(1, n + 1):
    for y in range(1, n + 1):
        print("{:5b} ".format(d), end="")
        d += 1
    print()
5 2 votes
Rate this Program
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments