Monday, 4 July 2016

How To Find Factorial In Java

How To Find Factorial In Java
What is Factorial?
Factorial means the product of a given positive integer multiplied by all lesser positive integers.
In This post, we will find Factorial of an Integer in java with some simple codes so first, we will understand what is factorial?
1! = 1
2! = 2*1
3! = 3*2*1
4! = 4*3*2*1
5! = 5*4*3*2*1


import java.util.Scanner;

class Factorial
{
   public static void main(String args[])
   {
      int a, c, fact = 1;

      System.out.println("Enter an integer to calculate it's factorial");
      Scanner in = new Scanner(System.in);

      a = in.nextInt();

      if ( a < 0 )
         System.out.println("Number should be non-negative.");
      else
      {
         for ( c = 1 ; c <= a ; c++ )
            fact = fact*c;

         System.out.println("Factorial of "+a+" is = "+fact);
      }
   }
}

Factorial Program Using Loop In Java

class FactorialExample{
 public static void main(String args[]){
  int i,fact=1;
  int number=5;//It is the number to calculate factorial
  for(i=1;i<=number;i++){
      fact=fact*i;
  }
  System.out.println("Factorial of "+number+" is: "+fact);
 }
}

Factorial Program Using Recursion
Here is the another Factorial Program in Java Using Recursion. But first we will understand what recursion is?
Q: What is recursion?
Recursion is a basic programming technique  use in Java, in recursion  a method calls itself to solve some problem. A process that uses this technique is recursive.


class FactorialExample2{
 static int factorial(int n){
  if (n == 0)
    return 1;
  else
    return(n * factorial(n-1));
 }
 public static void main(String args[]){
  int i,fact=1;
  int number=4;//It is the number to calculate factorial
  fact = factorial(number);
  System.out.println("Factorial of "+number+" is: "+fact);
 }

Friday, 24 June 2016

How To Make a Moving Car in C Graphics

This Code will make a moving car on your console screen .


#include<graphics.h>
#include<dos.h>
#include<conio.h>

main()
{
int i,j = 0, gd = DETECT,gm;
initgraph(&gd,&gm,"C:\\TC\\BGI");

settextstyle(DEFAULT_FONT,HORIZ_DIR,2);
outtextxy(25,240,"press any key to see moving car");

getch();


setviewport(0,0,839,440,1);
/*program details

author:sachin pandey

     */
for(i = 0 ; i <=500 ; i = i+10,j++)
{
//upward roof line
line(150+i,250,300+i,250);
  // downward roof line
line(50+i,300,420+i,300);
//left side window line
line(150+i,250,100+i,300);
//right side window line
line(300+i,250,350+i,300);

line(50+i,300,50+i,355);
line(50+i,355,420+i,355);
line(420+i,300,420+i,355);
circle(100+i,355,20);
circle(350+i,355,20);

setcolor(j);
delay(100);

if(i ==500)
break;
clearviewport();
}
getch();
closegraph();
return 0;
}

Another Program 



#include <stdio.h>
#include <graphics.h>
#include <conio.h>
#include <dos.h>

int main() {
    int gd = DETECT, gm;
    int i, maxx, midy;

    initgraph(&gd, &gm, "X:\\TC\\BGI");

    maxx = getmaxx();
 
    midy = getmaxy()/2;

    for (i=0; i < maxx-150; i=i+5) {
        cleardevice();

 
        setcolor(WHITE);
        line(0, midy + 37, maxx, midy + 37);

     
        setcolor(YELLOW);
        setfillstyle(SOLID_FILL, RED);

        line(i, midy + 23, i, midy);
        line(i, midy, 40 + i, midy - 20);
        line(40 + i, midy - 20, 80 + i, midy - 20);
        line(80 + i, midy - 20, 100 + i, midy);
        line(100 + i, midy, 120 + i, midy);
        line(120 + i, midy, 120 + i, midy + 23);
        line(0 + i, midy + 23, 18 + i, midy + 23);
        arc(30 + i, midy + 23, 0, 180, 12);
        line(42 + i, midy + 23, 78 + i, midy + 23);
        arc(90 + i, midy + 23, 0, 180, 12);
        line(102 + i, midy + 23, 120 + i, midy + 23);
        line(28 + i, midy, 43 + i, midy - 15);
        line(43 + i, midy - 15, 57 + i, midy - 15);
        line(57 + i, midy - 15, 57 + i, midy);
        line(57 + i, midy, 28 + i, midy);
        line(62 + i, midy - 15, 77 + i, midy - 15);
        line(77 + i, midy - 15, 92 + i, midy);
        line(92 + i, midy, 62 + i, midy);
        line(62 + i, midy, 62 + i, midy - 15);
        floodfill(5 + i, midy + 22, YELLOW);
        setcolor(BLUE);
        setfillstyle(SOLID_FILL, DARKGRAY);
     
        circle(30 + i, midy + 25, 9);
        circle(90 + i, midy + 25, 9);
        floodfill(30 + i, midy + 25, BLUE);
        floodfill(90 + i, midy + 25, BLUE);
        /* Add delay of 0.1 milli seconds */
        delay(100);
    }

    getch();
    closegraph();
    return 0;
}

Thursday, 16 June 2016

How to swap two number in java (using temporary or third variable)

How to swap two number  in java (using temporary or third variable)
Here we will learn how to swap two number using a third variable or temporary variable. The basic rule of swapping is first we take three variable and "temp, a, b," and  we use to store user's variable in "a" or "b" . after storing variable in "a" "b" we will store the value of "a"  in "temp" and in "a" we will store value of "b" and in "b"  we will store the value of "temp "  and than print the value of "a" and "b" .  So enjoy the code happy coding :)

    temp = a;
    a = b;
    b = temp;


Here is the code for swapping using a third variable:-


import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int A, B, temp;
        System.out.print("Enter an integer value for A: ");
        A = input.nextInt();
        System.out.print("Enter an integer value for  B: ");
        B = input.nextInt();
        System.out.println("Before: A = " + A + "   B = " + B);
   
        temp = A;
        A = B;
        B = temp;
     
        System.out.println("After: A = " + A + "   B = " + B);
    }
}

Another Program To Swap Two Number

 
import java.util.Scanner;
public class JavaProgram
{
    public static void main(String args[])
    {
        int num1, num2, swap;
        Scanner scan = new Scanner(System.in);
 
        System.out.print("Enter Two Number : ");
 
        System.out.print("\nFirst Number : ");
        num1 = scan.nextInt();
        System.out.print("Second Number : ");
        num2 = scan.nextInt();
 
        swap = num1;
        num1 = num2;
        num2 = swap;
 
        System.out.print("The Value of the First and Second Number after Swapping is \n");
 
        System.out.print("First Number = " +num1);
        System.out.print("\nSecond Number = " +num2);
    }
}


If you like the program of swapping two number in java ,share with your friends.
And if you find any errors in this program please comment below and lets us know.

You May Also Like: -

Java Program For Linear Search

Java Program For Linear Search

How To Reverse An Array In Java

Tuesday, 14 June 2016

How to Find percentage and grade of student in java

How to  find percentage and grade of student in java 

How to find  or calculate students grade or marks ? here is the code which help you to solve this problem. This program is mainly asked by us, after having the very basic concept of java programming language. It helps to find the percentage of  students in six subjects, and on the basis of there percentage this program classify the grades that is to be given to student.

Java program to finds percentage and grade of student entered by user

/*program to calculate grade of the student.
*/

import java.io.*;
public class AQ18
{
public static void main(String args[])throws IOException
{
InputStreamReader read= new InputStreamReader(System.in);
BufferedReader in= new BufferedReader(read);
String name[]=new String[100];
int roll[]=new int[100];
int s1[]=new int[100];
int s2[]=new int[100];
int s3[]=new int[100];
int s4[]=new int[100];
int s5[]=new int[100];
int s6[]=new int[100];
double p[]=new double[100];
int i;
for(i=0;i<100;i++)
{
System.out.println("Enter the roll no.");
roll[i]=Integer.parseInt(in.readLine());
System.out.println("Enter the name");
name[i]=in.readLine();
System.out.println("Enter the marks of 1st Subject");
s1[i]=Integer.parseInt(in.readLine());
System.out.println("Enter the marks of 2nd Subject");
s2[i]=Integer.parseInt(in.readLine());
System.out.println("Enter the marks of 3rd Subject");
s3[i]=Integer.parseInt(in.readLine());
System.out.println("Enter the marks of 4th Subject");
s4[i]=Integer.parseInt(in.readLine());
System.out.println("Enter the marks of 5th Subject");
s5[i]=Integer.parseInt(in.readLine());
System.out.println("Enter the marks of 6th Subject");
s6[i]=Integer.parseInt(in.readLine());
}
for(i=0;i<100;i++)
{
p[i]=(s1[i]+s2[i]+s3[i]+s4[i]+s5[i]+s6[i])*100/600;
System.out.println("Roll no. : "+roll[i]);
System.out.println("Name : "+name[i]);
System.out.println("Percentage : "+p[i]);
if(p[i]>=80 && p[i]<=100)
{
System.out.println("Grade : A");
}
else if(p[i]>=60 && p[i]<80)
{
System.out.println("Grade : B");
}
else if(p[i]>=40 && p[i]<60)
{
System.out.println("Grade : C");
}
else
System.out.println("Grade : D");
}
}
}
}

Another Program


{
 public static void main(String args[])
 {
  int maths, physics, chem, hindi, english;
  maths = Integer.parseInt(args[0]);
  physics = Integer.parseInt(args[1]);
  chem = Integer.parseInt(args[2]);
  hindi = Integer.parseInt(args[3]);
  english = Integer.parseInt(args[4]);
 
  float sum = maths + physics + chem + hindi + english;
  
  System.out.println(&quot;Total marks &quot; +sum);
 
  float per= sum/5;
 
  System.out.println(&quot;Percentage is &quot;+per);
 
  if(per&gt;=65)
  {
   System.out.println(&quot;Ist divison&quot;);
  }
  else if(per &gt;=55 &amp;&amp; per &lt;65)
  {
   System.out.println(&quot;IInd division&quot;);
  }
  else if(per &gt;=40 &amp;&amp; per &lt;55)
  {
   System.out.println(&quot;IIIrd divison&quot;);
  }
  else
  {
   System.out.println(&quot;Fail&quot;);
  }
 }
}

If You Find This Program Helpful leave A Comment And Do Share With Your Friends.

You May Also Like : -

Odd Even Number In Java

Java Program To Bubble Sort

Reverse Number In Java

Code for floyad's triangle in java

Code for floyad's triangle in java

Floyad's triangle printing in java :-Floyd's triangle is a right-angled triangular array of natural numbers, used in computer science education. It is named after Robert Floyd. It is defined by filling the rows of the triangle with consecutive numbers, starting with a 1 in the top left corner:

1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

code for floyafd's triangle


import java.util.Scanner;

class FloydTriangle
{
   public static void main(String args[])
   {
      int n, num = 1, i, j;
      Scanner in = new Scanner(System.in);

      System.out.println("Enter the number of rows of floyd's triangle:");
      n = in.nextInt();

      System.out.println("Floyd's triangle :");

      for ( i = 1 ; i <= n ; i++ )
      {
         for ( j = 1 ; j <= i ; j++ )
         {
            System.out.print(num+" ");
            num++;
         }

         System.out.println();
      }
   }
}

Another Program

class Floyad
{
    publicstaticvoid main(String args[])
    {
         int i,j,c;
         c=0;
           for(i=1;i<=5;i++)
            {
               c=i;
              for(j=1;j<=i;j++)
              {
                    if((c%2)==0)
                    {
                            System.out.print(0+" ");
                    }
                   else
                   {
                            System.out.print(1+" ");
                   }
                   c++;
             }
             System.out.println();
        }
       
    }
}

import java.util.Scanner;
public class FloydTriangle {
public static void main(String args[]) {
Scanner cmd = new Scanner(System.in);
System.out.println("Enter the number of rows of Floyd's triangle, you want to display");
int rows = cmd.nextInt();
printFloydTriangle(rows);
}
 public static void printFloydTriangle(int rows) {
int number = 1;
System.out.printf("Floyd's triangle of %d rows is : %n", rows);

for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(number + " ");
number++;
}
System.out.println();
}
}
}

If You Find This Program Helpful Leave A Comment And DO Share With Your Friends.

You May Also Like: - Swapping Two Number In Java

How To Find Odd Even Number In Java

Factorial In Java

Code for printing odd even number in java

Code for printing odd even number in java
Finding odd even number in java program :- so what is the logic behind this program ?
 As we have study in mathematics that in decimal number system even numbers are divisible by 2 while odd are not so we may use modulus operator(%) which returns remainder,  Even numbers are of the form 2*x and odd are of the form 2*x+1  suppose that x  is an integer.

public class FindEvenOrOddNumber {

        public static void main(String[] args) {
               
                /*create an array of 10 numbers*/
                int[] numbers = new int[]{1,2,3,4,5,6,7,8,9,10};
               
                for(int i=0; i < numbers.length; i++){
                       
                        /*
                         * use modulus operator to check if the number is even or odd. 
                         * If we divide any number by 2 and reminder is 0 then the number is
                         * even, otherwise it is odd.
                         */
                         
                         if(numbers[i]%2 == 0)
                                System.out.println(numbers[i] + " is even number.");
                         else
                                System.out.println(numbers[i] + " is odd number.");
                               
                }
               
        }
}

/*
Output of the program would be
1 is odd number.
2 is even number.
3 is odd number.
4 is even number.
5 is odd number.
6 is even number.
7 is odd number.
8 is even number.
9 is odd number.
10 is even number.
*/

Another odd-even program which takes input from user:-

import java.util.Scanner;

public class OddEven {

    
    public static void main(String args[]) {
        int num = 0;

        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
     
        num = sc.nextInt();

        if (num % 2 == 0) {
            System.out.println(num + " is even ");
        } else {
            System.out.println(num + " is odd ");
        }

    } 

Monday, 13 June 2016

How to find ASCII code for any input in c++

ASCII remains for American Standard Code For Information Interchange.ASCII codes speak to content in PCs media communications gear and different gadgets. ASCII was the most well-known character encoding on the World Wide Web until December 2007, when UTF-8 encoding outperformed it.


Program For finding ASCII Code

#include<iostream.h>

#include<ctype.h>

#include<conio.h>

int main(void)

{

   int number, result;

   clrscr();

   cout<<"Enter any Symbol/Character or number to know tits ASCII value: ";

   number = getch();

   result = toascii(number);

   cout<<"Ascii value of entered input is: "<<result;

   getch();

}

Another Program To Find ASCII code

#include <iostream>
using namespace std;

int main(){
char ascii;
int numeric;
cout << "Give character: ";
cin >> ascii;
cout << "Its ascii value is: " << (int) ascii << endl;
cout << "Give a number to convert to ascii: ";
cin >> numeric;
cout << "The ascii value of " << numeric << " is " << (char) numeric;
return 0;

}
Program 2


#include<iostream.h>
#include<conio.h>
int main()


{
char ch;
int ascii;
cout << "ENTER Any Character \n";
cin >> ch;
ascii = ch;

cout << ch <<"ASCII Code is = " << ascii ;


getch();
return 0;
}

if you find this program helpful leave a comment and do share with your friends.

You May Also Like:-
Program To Print Pascal Triangle In C++
How To Find Reverse Number In C++
How To Find Prime Number In C++


Sunday, 12 June 2016

How to find square root of a number in c++

How to find square root of a number in c++
Finding the square Root of a number is the backward operation of squaring that number. Keep in mind, the square of a number is that number circumstances itself. The ideal squares are the squares of the entire numbers. The square root of a number, n, composed beneath is the number that gives n when duplicated without anyone else's input.
This code of finding square root in c++ is the easiest way. if you like this program do a share with your friends, and don't forget to give feedback to us

C++ code for finding square root of a number


#include<iostream.h>

#include<conio.h>

#include<math.h>

void main()

{

int num,ans;

clrscr();

cout<<"Enter any Num: ";

cin>>num;

ans=pow(num,0.5);

cout<<"\n Squre of "<<num<<" is: "<<ans;

getch();

}


Passing Value To Function 



#include<iostream.h>
#include<conio.h>
#include<math.h>

int square(int);
void main()
{
int num;
clrscr();
cout<<"Enter any Num: ";
cin>>num;
cout<<"\n Square of "<<num<<" is: "<<square(num));
getch();
}
int square(int num)
{
int ans;
ans=pow(num,0.5);
return(ans);
getch();
}


Another Program For Finding Square Root Of A Number 


#include <iostream>
#include <cmath>
#include <limits>

int main()
{
    double output, input, min, max;

    std::cout << "Enter the value : ";
    std::cin  >> input;
    std::cout << std::endl;
    min = std::numeric_limits<double>::min();
    max = std::numeric_limits<double>::max();
    if (input >= min && input <= max)
    {
        output = sqrt(input);
        std::cout << "Square root of " << input
                  << " = " << output << std::endl;
    }
    else
    {
        std::cerr << "Error: " << input << " not within limits"
                  << std::endl;
    }
    return 0;
}

if you like this program do a comment and let us know.

You May Also Read:-
Reverse Number Program In C++
How To Find Prime Number In C++
How To Find GCD And HCF Of Two Numbers

Reverse number program in c++

A basic C++ program in which client enter a number, program switch it and show turned around the number on the support.

For instance: If input number is 12345

At that point turned around number will be 54321
This program reverses the number entered by the user and then prints the reversed number on the screen. For example, if user enter 123 as input then 321 is printed as output


Program For Reverse Number In C++

#include<iostream.h>
#include<conio.h>

void main()
{
int no,rev=0,r,a;
clrscr();
cout<<"Enter the num: ";
cin>>no;
a=no;
while(no>0)
{
 r=no%10;
 rev=rev*10+r;
 no=no/10;
}
cout<<"\nReverse of "<<a<<" is: "<<rev;
getch();
}


Another Program For Reversing An Integers


#include <iostream>
using namespace std;

int main()
{
    int n, reversedNumber = 0, remainder;

    cout << "Enter an integer: ";
    cin >> n;

    while(n != 0)
    {
        remainder = n%10;
        reversedNumber = reversedNumber*10 + remainder;
        n /= 10;
    }

    cout << "Reversed Number = " << reversedNumber;

    return 0;
}


Another Program To Reverse A Number In C++


#include <iostream>

using namespace std;

class Operations
{
  long c;

public:
  void inputNumber()
  {
    cout << "Input a number\n";
    cin >> c;
  }

  long reverseNumber()
  {
    long invert = 0;

    while (c != 0)
    {
      invert = invert * 10;
      invert = invert + c%10;
      c = c/10;
    }

    return invert;
  }

};

int main()
{
  long result;

  Operations t;
  t.inputNumber();
  result = t.reverseNumber();

  cout << "Number obtained on reversal = " << result;

  return 0;
}

If You Find This Program Helpful Leave A Comment and Do Share with Your Friends

You May Also Like:
Square RooT Of A Number In C++
How To Find Prime Number In C++

How to find prime number in C++

prime number program in c++ :- A prime number is a whole number greater than 1, whose only two whole-number factors are 1 and itself. The first few prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23, and 29. As we proceed in the set of natural numbers N = {1, 2, 3, ...}, the primes become less and less frequent in general

Code For The Prime Number In C++



#include<iostream.h>
#include<conio.h>

void main()
{
  int i,no;
  clrscr();
  cout<<"Enter any num: ";
  cin>>no;
  if(no==1)
  {
  cout<<"Smallest prime num is 2";
  }
  for(i=2;i<no;i++)
  {
  if(no%i==0)
  {
  cout<<"Not prime num";
  break;
  }
  }
 if(no==i)
 {
 cout<<"Prime num";
 }
  getch();
}


Another Program For Finding  Prime Number In C++

#include <iostream>
using namespace std;

int main()
{
  int n, i;
  bool isPrime = true;

  cout << "Enter a positive integer: ";
  cin >> n;

  for(i = 2; i <= n / 2; ++i)
  {
      if(n % i == 0)
      {
          isPrime = false;
          break;
      }
  }
  if (isPrime)
      cout << "This is a prime number";
  else
      cout << "This is not a prime number";

  return 0;
}

If You Find the program helpful leave a comment and do a share with your friends
You may Also Like:

Reverse Number Program In C++
How To Find GCD Or HCF Of Two Numbers In C++

Same Program In Another language

How To Check Prime Number In Java

Program to Print Pascal Triangle in c++

Program to Print Pascal Triangle in c++

what is pascal triangle: - In science, Pascal's triangle is a triangular cluster of the binomial coefficients. In the Western world, it is named after French mathematician Blaise Pascal, albeit different mathematicians contemplated it hundreds of years before him in India, Persia (Iran), China, Germany, and Italy.

To build the triangle, start with "1" at the top, then continue placing numbers below it in a triangular pattern.

code for pascal triangle in c++


pascal triangle

#include<iostream.h>
#include<conio.h>

void main()
{
int bin,p,q,r,x;
clrscr();
bin=1;
q=0;
cout<<"\t\t\tDisplay pascal Triangle";
cout<<"\n\n\t\t  ";
cout<<"\n\n\nHow Many Row Do you want to input:";
cin<<r;

cout<<"\nPascal's Triangle:\n";

while(q<r)
{
for(p=40-3*q;p>0;--p)
cout<<" ";
for(x=0;x<=q;++x)
{
if((x==0)||(q==0))
bin=1;
else
bin=(bin*(q-x+1))/x;
cout<<"      ";
cout<<bin;
}

cout<<"\n\n\n";
++q;
}
getch();
}


Another Program For Printing Pascal Triangle In C++


#include<iostream>
using namespace std;

int main()
{
    int rows;
    cout << "Enter the number of rows : ";
    cin >> rows;
    cout << endl;

    for (int i = 0; i < rows; i++)
    {
        int val = 1;
        for (int j = 1; j < (rows - i); j++)
        {
            cout << "   ";
        }
        for (int k = 0; k <= i; k++)
        {
            cout << "      " << val;
            val = val * (i - k) / (k + 1);
        }
        cout << endl << endl;
    }
    cout << endl;
    return 0;
}


This is our small effort to help you if you like this code plz do follow me and share this code with your friends.
You may Also Like: -

Fibonacci Series In C++
Program For Reverse Number In C++
How To Find Prime Number In C++


C++ Program To Find GCD or HCF Of Two Numbers


C++ Program to Find HCF of two numbers: HCF means Highest Common Factor
GCD stands for Greatest Common Divisor. GCD is the largest number that divides the given numbers.
Step 1: Find the divisors of given numbers:
Step 2: Find the greatest number that these two lists share in common. In this example, the GCD is 9.
LCM stands for Lowest Common Multiple.

#include<iostream.h>
#include<conio.h>

void gcd(int,int);

void main()
{
    int a,b;
    clrscr();
    cout<<"Enter two numbers: ";
    cin>>a>>b;
    gcd(a,b);
    getch();
  //  return 0;
}

//main function for calculating g.c.d
void gcd(int a,int b)
{
    int m,n;

    m=a;
    n=b;

    while(m!=n)
    {
        if(m>n)
            m=m-n;
        else
            n=n-m;
    }

    cout<<"\nH.C.F of"<<a<<" & "<<b<<" is "<<m;
}

Another program


#include <iostream>

using namespace std;
 
int getGcd(int a, int b);

int main(){
    int num1, num2, gcd;
   
 cout << "Enter two numbers\n";
    cin >> num1 >> num2;
   
    gcd = getGcd(num1, num2);

    cout << "GCD of " << num1 << " and " << num2 << " is " << gcd;

    return 0;
}
/*
 *his is the Function to calculate Greatest Common Divisor of two number
 */
 int getGcd(int a, int b) {
  if (b == 0) {
    return a;
  }
  else {
    return getGcd(b, a % b);
  }
}





Convert Celsius to Fahrenheit in c++

Simple C++ Program to Convert Celsius to Fahrenheit:
To convert temperatures in degrees Celsius to Fahrenheit, first we have to understand the logic behind this method of conversion. so for converting celsius to Fahrenheit, we have to multiply by 1.8 (or 9/5) and add 32.
in this post, we will learn to convert temperatures from Degree to Celsius.




#include<iostream.h>
#include<conio.h>

void main()
{
 float cel, far;
  clrscr();
  cout<<"Enter temp. in Celsius: ";
  cin>>cel;
   far = cel * 9/5 + 32;
  cout<<"Temp. in Fahrenheit: "<<far;
 getch();
}

Another temperature converter program in c++

This is second program for converting temperature celsius to fahrenheit.

#include <iostream>
using namespace std;
float celsius;
float fahrenheit;

void convertF()
{
celsius = ((fahrenheit - 32) * 5) / 9;
}
void convertC()
{
fahrenheit = (((celsius * 9) / 5) + 32);
}

int main()
{
unsigned short choice;
cout << "Welcome to the temperature converter.\n";
cout << "Please type '1' for Celsius to Fahrenheit conversion." << endl;
cout << "Or, type '2' for Fahrenheit to Celsius conversion." << endl;
cin >> choice;

switch (choice)
{
case 1:

cout << "Please enter your temperature in Celsius.\n";

cin >> celsius;
convertC();

cout << "\n";
cout << "Computing...\n\n";
cout << "The temperature in Fahrenheit is " << fahrenheit << ".\n";
cout << "Press any key to terminate the program." << endl;
cout << endl;
break;

case 2:

cout << "Please enter your temperature in Fahrenheit.\n";

cin >> fahrenheit;
convertF();

cout << "\n";
cout << "Computing...\n\n";
cout << "The temperature in Celsius is " << celsius << ".\n";
cout << "Press any key to terminate the program." << endl;
cout << endl;
break;

default:

cout << "That is not an option!" << endl;
cout << "Please close the program and try again." << endl;
break;

}

return 0;
}

If You Like The Program Leave A Comment And Do Share With Your Friends and If You Have Any Query Related To This Program You Can Comment Below. Thank You Happy Coding. :)

You May Also Like: -

How To Find Prime Number In C++

Pascal Triangle In C++

How To Find Reverse Number In C++


fibonacci series in C++

 what is fibonacci series ? fibonacci series is  a series of numbers in which each number ( Fibonacci number ) is the sum of the two preceding numbers. The simplest is the series 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 etc. The first two numbers of fibonacci series are 0 and 1.

Code For Fibonacci Series


#include<iostream.h>
#include<conio.h>

void main()
{
int i,no, first=0, second=1, next;
clrscr();
first=0;
second=1;
cout<<"Enter nubmer of terms for Series: ";
cin>>no;
cout<<"Fibonacci series are: \n";
for(i=0; i<no; i++)
{
cout<<"\n"<<first;
next = first + second;
first = second;
second = next;
}
getch();
}

Fibonacci Series Upto N Numbers



#include <iostream>
using namespace std;

int main()
{
    int n, t1 = 0, t2 = 1, nextTerm = 0;

    cout << "Enter the number of terms: ";
    cin >> n;

    cout << "Fibonacci Series: ";

    for (int i = 1; i <= n; ++i)
    {
        // Prints the first two terms.
        if(i == 1)
        {
            cout << " " << t1;
            continue;
        }
        if(i == 2)
        {
            cout << t2 << " ";
            continue;
        }
        nextTerm = t1 + t2;
        t1 = t2;
        t2 = nextTerm;
     
        cout << nextTerm << " ";
    }
    return 0;
}


Program To Generate Fibonacci Series Of Given Numbers


#include <iostream>
using namespace std;

int main()
{
    int t1 = 0, t2 = 1, nextTerm = 0, n;

    cout << "Enter a positive integer: ";
    cin >> n;

    // displays the first two terms which is always 0 and 1
    cout << "Fibonacci Series: " << t1 << ", " << t2 << ", ";

    nextTerm = t1 + t2;

    while(nextTerm <= n)
    {
        cout << nextTerm << ", ";
        t1 = t2;
        t2 = nextTerm;
        nextTerm = t1 + t2;
    }
    return 0;
}


If You Found This Program Helpful Please leave a Comment And Do share with your friends

You May Also Like: -

Saturday, 11 June 2016

Email Address validation in javascript

Email Address Validation In JavaScript is a vary important program always asked by us.
if you have any suggestion related to this program let us know by doing a comment.
validate email address in your school project or in any project by simply using this code

function Validate_String(string, return_invalid_chars)
         {
         valid_chars = '1234567890-_.^~abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
         invalid_chars = '';
       
         if(string == null || string == '')
            return(true);
       
         //For every character on the string.
         for(index = 0; index < string.length; index++)
            {
            char = string.substr(index, 1);                      
         
            //Is it a valid character?
            if(valid_chars.indexOf(char) == -1)
              {
              //If not, is it already on the list of invalid characters?
              if(invalid_chars.indexOf(char) == -1)
                {
                //If it's not, add it.
                if(invalid_chars == '')
                   invalid_chars += char;
                else
                   invalid_chars += ', ' + char;
                }
              }
            }                  
         
         //If the string does not contain invalid characters, the function will return true.
         //If it does, it will either return false or a list of the invalid characters used
         //in the string, depending on the value of the second parameter.
         if(return_invalid_chars == true && invalid_chars != '')
           {
           last_comma = invalid_chars.lastIndexOf(',');
         
           if(last_comma != -1)
              invalid_chars = invalid_chars.substr(0, $last_comma) +
              ' and ' + invalid_chars.substr(last_comma + 1, invalid_chars.length);
                   
           return(invalid_chars);
           }
         else
           return(invalid_chars == '');
         }


function Validate_Email_Address(email_address)
         {
         //Assumes that valid email addresses consist of user_name@domain.tld
         at = email_address.indexOf('@');
         dot = email_address.indexOf('.');
       
         if(at == -1 ||
            dot == -1 ||
            dot <= at + 1 ||
            dot == 0 ||
            dot == email_address.length - 1)
            return(false);
         
         user_name = email_address.substr(0, at);
         domain_name = email_address.substr(at + 1, email_address.length);                
       
         if(Validate_String(user_name) === false ||
            Validate_String(domain_name) === false)
            return(false);                  
       
         return(true);
         }
       
function Validate(email)
         {
         valid = Validate_Email_Address(email);

         if(valid == true)
            document.email.valid.value = 'valid';
         else
            document.email.valid.value = 'invalid';
         }    
If You Found This Program Helpful Leave A Comment And Do Share With Your Friends.  

Friday, 10 June 2016

Code for Count down clock in JavaScript

Count down clock in javascript :- Allows you to place a countdown to any future date of your choice on your website.

function countdown_clock(year, month, day, hour, minute, format)
         {
         //I chose a div as the container for the timer, but
         //it can be an input tag inside a form, or anything
         //who's displayed content can be changed through
         //client-side scripting.
         html_code = '<div id="countdown"></div>';
     
         document.write(html_code);
     
         countdown(year, month, day, hour, minute, format);            
         }
     
function countdown(year, month, day, hour, minute, format)
         {
         Today = new Date();
         Todays_Year = Today.getFullYear() - 2000;
         Todays_Month = Today.getMonth();              
     
         //Convert both today's date and the target date into miliseconds.                      
         Todays_Date = (new Date(Todays_Year, Todays_Month, Today.getDate(),
                                 Today.getHours(), Today.getMinutes(), Today.getSeconds())).getTime();                            
         Target_Date = (new Date(year, month - 1, day, hour, minute, 00)).getTime();              
     
         //Find their difference, and convert that into seconds.              
         Time_Left = Math.round((Target_Date - Todays_Date) / 1000);
     
         if(Time_Left < 0)
            Time_Left = 0;
     
         var innerHTML = '';
     
         switch(format)
               {
               case 0:
                    //The simplest way to display the time left.
                    innerHTML = Time_Left + ' seconds';
                    break;
               case 1:
                    //More datailed.
                    days = Math.floor(Time_Left / (60 * 60 * 24));
                    Time_Left %= (60 * 60 * 24);
                    hours = Math.floor(Time_Left / (60 * 60));
                    Time_Left %= (60 * 60);
                    minutes = Math.floor(Time_Left / 60);
                    Time_Left %= 60;
                    seconds = Time_Left;
               
                    dps = 's'; hps = 's'; mps = 's'; sps = 's';
                    //ps is short for plural suffix.
                    if(days == 1) dps ='';
                    if(hours == 1) hps ='';
                    if(minutes == 1) mps ='';
                    if(seconds == 1) sps ='';
               
                    innerHTML = days + ' day' + dps + ' ';
                    innerHTML += hours + ' hour' + hps + ' ';
                    innerHTML += minutes + ' minute' + mps + ' and ';
                    innerHTML += seconds + ' second' + sps;
                    break;
               default:
                    innerHTML = Time_Left + ' seconds';
               }              
               
            document.getElementById('countdown').innerHTML = innerHTML;
           
         //Recursive call, keeps the clock ticking.
         setTimeout('countdown(' + year + ',' + month + ',' + day + ',' + hour + ',' + minute + ',' + format + ');', 1000);
         }

If You Find This Program Helpful Leave A Comment And Do Share With Your Friends.
Or If You Have Any Query Related To This Program Comment below . Happy Coding.


You May Also Like : -

Fibonacci Series In JavaScript


How to find given year is leap year or not

A leap year is a calendar year containing one extra day added to keep the calendar year synchronized with the cosmic or occasional year.Because seasons and galactic occasions don't rehash in an entire number of days, schedules that have a similar number of days in every year float after some time as for the occasion that the year should track. By embeddings (likewise called intercalating) an extra day or month into the year, the float can be remedied.
A leap year in the Gregorian calendar has an extra day for February.
 A leap year has 366 days.

 * Algorithm to find a leap year
  -------------------------------
   if year % 400 = 0, leap year
   else if year % 100 = 0, not a leap year
   else if year % 4 = 0, leap year
   else, not a leap year

public class LeapYearCalculator
{
    public static void main(String args[])
    {

        /*Give the year here which needs to be checked for leap year
         * (Assuming that year given here  >= 1582 and corresponds to a year in Gregorian calendar)
         */
        int year = 2000;

        //Flag to store the test result
        boolean isLeapYear = false;

        if(year % 400 == 0)
        {
            isLeapYear = true;
        }
        else if (year % 100 == 0)
        {
            isLeapYear = false;
        }
        else if(year % 4 == 0)
        {
            isLeapYear = true;
        }
        else
        {
            isLeapYear = false;
        }

        //Output the test result
        if(isLeapYear)
        {
            System.out.println("Year "+year+" is a Leap Year");
        }
        else
        {
            System.out.println("Year "+year+" is not a Leap Year");
        }

    }
}

if you find this program helpful leave a comment and share this with your friends. thank you

Thursday, 9 June 2016

Java Program To Bubble Sort

This code sorts numbers inputted by user using Bubble sort algorithm.

 Bubble Sort Algorithm
Consider a list of items in an array which needs to be sorted. The Bubble sort starts by keeping a cursor at the left most item of the array, let’s say, at position 0. It compares it with an item adjacent to it at a position 0+1. If the item at position 0 is greater, it swaps these two elements, else it does nothing. The cursor, then moves to the next position in the array. It moves and compares the two adjacent items in the array until it reaches the right end of the array, when the greatest item in the array is placed in its sorted position N-1. After the first pass, we would made N-1 comparison and swaps between 0 to N-1.

The cursor then, starts with the left most item of the array and repeats the process of comparing and swapping until the item reaches its proper sorted position. This time it stops at position N-2. This is because the last item at N-1 is already sorted.
It continues this process until all the items in the array are placed in their sorted order.



public class BubbleSortAscendingOrderDemo
{

    public static void main(String a[])
    {
        //Numbers which need to be sorted
        int numbers[] = {23,5,23,1,7,12,3,34,0};

        //Displaying the numbers before sorting
        System.out.print("Before sorting, numbers are ");
        for(int i = 0; i < numbers.length; i++)
        {
            System.out.print(numbers[i]+" ");
        }
        System.out.println();

        //Sorting in ascending order using bubble sort
        bubbleSortInAscendingOrder(numbers);

        //Displaying the numbers after sorting
        System.out.print("Before sorting, numbers are ");
        for(int i = 0; i < numbers.length; i++)
        {
            System.out.print(numbers[i]+" ");
        }

    }

    //This method sorts the input array in ascending order

    public static void bubbleSortInAscendingOrder( int numbers[])
    {
        int temp;

        for(int i = 0; i < numbers.length; i++)
        {
            for(int j = 1; j < (numbers.length -i); j++)
            {
                //if numbers[j-1] > numbers[j], swap the elements
                if(numbers[j-1] > numbers[j])
                {
                    temp = numbers[j-1];
                    numbers[j-1]=numbers[j];
                    numbers[j]=temp;
                }
            }
        }
    }

}

Java code to print system time and date

Java code to print or display current system date and time. This program prints current date and time.


Java code to print system time and date


import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtil
{
  public static void main( String[] args ) {

    //Approach 1 to get date and time
    Date date1 = new Date();
    System.out.println(date1);

    //Approach 2 to get date and time
    Calendar calendar = Calendar.getInstance();
    Date date2 = calendar.getTime();
    System.out.println(date2);

    //Displaying the date and time - dd/MM/yyyy
    DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
    String dateFormatted = dateFormat.format(date1);
    System.out.println(dateFormatted);

    //Displaying the date and time - E, dd MMM yyyy HH:mm:ss Z
    dateFormat = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z");
    dateFormatted = dateFormat.format(date1);
    System.out.println(dateFormatted);


    //Displaying the date and time - dd-MM-yyy
    dateFormat = new SimpleDateFormat("dd-MM-yyyy");
    dateFormatted = dateFormat.format(date1);
    System.out.println(dateFormatted);

  }
}

Another Program To Print System Time And Date

import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class GettingCurrentDate {
   public static void main(String[] args) {
       //getting current date and time using Date class
       DateFormat df = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
       Date dateobj = new Date();
       System.out.println(df.format(dateobj));

       /*getting current date time using calendar class
        * An Alternative of above*/
       Calendar calobj = Calendar.getInstance();
       System.out.println(df.format(calobj.getTime()));
    }
}

If You Find This Program Helpful Leave A Comment And Do Share With Your Friends.

You May Also Like : -



How to find reverse number in java

This program reverse the number entered by the user and then prints the reversed number on the screen. For example if user enter 123 as input then 321 is printed as output.

import java.util.*;

class ReverseString
{
   public static void main(String args[])
   {
      String original, reverse = "";
      Scanner in = new Scanner(System.in);

      System.out.println("Enter a string to reverse");
      original = in.nextLine();

      int length = original.length();

      for ( int i = length - 1 ; i >= 0 ; i-- )
         reverse = reverse + original.charAt(i);

      System.out.println("Reverse of entered string is: "+reverse);
   }
}

How to swap two number using call by reference in c

Learn how to swap Two number using call by reference in C with our simple program.You can Swap two number also with using third variable. Swaping two numbers using call by reference in c is a very important program.


This program swaps two numbers entered by the user using call by reference.


#include<stdio.h>
#include<conio.h>
void swap(int *,int *);
void main()
{
 int a,b,temp,*x,*y;
 clrscr();
 printf("Enter value of a and b\n");
 scanf("%d\n%d",&a,&b);
 printf("Initial Values:\na = %d\nb = %d\n",a,b);
 swap(&a,&b);
 printf("After swapping:\na = %d\nb = %d\n",a,b);
 getch();
}
void swap(int *x,int *y)
{
 int temp;
 temp=*y;
 *y=*x;
 *x=temp;
}





Another Program To Swap Two Numbers Using Call By Reference

#include<stdio.h>

int swap(int *ptr1, int *pt2);

int main()
{
        int num1, num2;
        printf("\nEnter The First Number:\t");
        scanf("%d", &num1);
        printf("\nEnter The Second Number:\t");
        scanf("%d", &num2);
        swap(&num1, &num2);
        printf("\nThe Swapped Values are:\n");
        printf("First Number = %d and Second Number = %d\n", num1, num2);
        return 0;
}

int swap(int *ptr1, int *ptr2)
{
        int temp;
        temp = *ptr1;
        *ptr1 = *ptr2;
        *ptr2 = temp;
}




How to check prime number in java

A prime number is a whole number greater than 1, whose only two whole-number factors are 1 and itself. The first few prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23, and 29. As we proceed in the set of natural numbers N = {1, 2, 3, ...}, the primes become less and less frequent in general.

import java.util.*;

class PrimeNumbers
{
   public static void main(String args[])
   {
      int n, status = 1, num = 3;

      Scanner in = new Scanner(System.in);
      System.out.println("Enter the number of prime numbers you want");
      n = in.nextInt();

      if (n >= 1)
      {
         System.out.println("First "+n+" prime numbers are :-");
         System.out.println(2);
      }

      for ( int count = 2 ; count <=n ;  )
      {
         for ( int j = 2 ; j <= Math.sqrt(num) ; j++ )
         {
            if ( num%j == 0 )
            {
               status = 0;
               break;
            }
         }
         if ( status != 0 )
         {
            System.out.println(num);
            count++;
         }
         status = 1;
         num++;
      }        
   }
}