Sunday, May 17, 2015

Basic Programs in C Language

C is a popular programming language from modern languages and
it seed of modern programming languages(like c++,java,etc).
C language is developed by Dennis Ritchie at AT&T Bell Labs.
This language is used to write the chip level programs and drivers code.C is a basic language to improve programming skills.Because to improve our coding skills, we should learn C language from fundamental(Data types,loops,etc) to high level(Read file from local drive).Means all modern languages have their own predefined methods.For example if we want to sort the array elements in java we have sort method but C language doesn't have that type of functions .So we want improve our coding skills we learn C language from basic level. That's why,I am giving basic fundamental programs to improve our programming skills.Now a days, in every interviewer will ask at least two or three questions from C language irrespective of you attending programming language interview(Java,.Net,Ruby,etc).Let's us start with basic programming questions.



When i am learning C language,my first executed program is Hello World Program.Who will learn this language first time,they run Hello World program before running any other program.Now i will explain our first program with step by step.

1)First line of program has header files.Header files are contains some basic predefined function to execute our program.



#include <stdio.h>
means here we including stdio.h header file to compiler for compile and run program.This file has standard input ,output functions.For example input function is scanf,this is used to read characters from client. And output function is to print on the command line.
2)
void main()
{
   //some code
}
Our actual program will start with main() function only.Program execution start from main().void is a predefined keyword which returns nothing."{","}"are indicates where program starting ,where program ending respectively.

3) We write one predefined function in the place of some code in step 2.That is printf("Hello World");
printf() is a standard output function in C language.It is available in stdio.h,that's why we included stdio.h in program.

Let's see below program

1)#include<stdio.h>

void main(){
printf("Hello World");// this function display the "Hello World" on console.
}

Output:
Hello World

2)Write a  C program for add two integer numbers?
/**
 * Adding two integer numbers
* @ author rrvtechdiamond
*/
#include<stdio.h>
void main()
{
  //here declare 'a'  variable with  "int"  data type and assign value 6 to variable 'a'
   int a = 6;
   int b = 5;//here declare 'b' variable with  "int"  data type and assign value 5 to variable 'b'
   int c = 0;//here declare 'c' variable with  "int"  data type and assign zero to 'c' variable 
   c = a+b;//assign addition of two numbers to ' c' variable
   printf("The addition of two integers is:%d",c);//  print the result on console
   getch();


Output:
The addition of two integers is:11

3)Find the difference of two numbers using C program?

#include<stdio.h>

void main(){
     int a = 10;
     int b = 5;
     int c = a-b;
     printf("The Subtraction of two numbers is:  %d",c);
     getch();
}

Output:
The Subtraction of two numbers is: 5

4)Find the biggest number among 3 number using  C program?

#include<stdio.h>

void main()
{
   int a = 1,b = 10, c =  6;  // here declare and assign three variables with different values
 if(a > b && a > c){ //Here && operator is used like a logical AND means if both conditions are                                      //true then only this block  will execute 
     printf("The biggest number is: %d",a);
 }else if(b > a && b > c){
    printf("The biggest number is: %d",b);
}else //here  no need to check because above two conditions are not execute then this block will               //execute then which value is contains c that is bigger
    printf("The biggest number is: %d",c);
}

}

Output :
The biggest number is: 10

Let's see here up to now  declaring values directly in program.But up coming programs are read variable values from console.Then see below programs.

5)How to read values from console using C program?
 #include<stdio.h>
void main(){
int  a;//here declare two variables a and b
int b;
printf("Enter  a and b values");
scanf("%d",&a); //scanf function is predefined library function is used to read data from console /                            //and printf() function is also predefined function is used to print data on console
scanf("%d",&b);//here %d is used to represent integer values and generally we declare variable //like a or b or c then &a means address of variable.When we enter value in console that value is //stored into this address place .

printf("You entered values are %d,%d",a,b);

}

Output:

Enter a and b values 10
15

You entered values are 10,15

6)Find the given number is even or not using ternary operator?

First we should know what is ternary operator.Means we use three operands.Syntax of this one is

Syntax:
(condition) ? if true this : if false this;

Ex:

int a = 10;
int b = 3;
(a>b)?a :b;
Output:
10

Let see the program


#include<stdio.h>

void main(){
int a;
printf("Please enter number:");
scanf("%d",&a);
(a%2 == 0)?printf("The given number %d is even number ",a):printf("The given number  %d is not even number",a);

getch();

}

Output:

1)Please enter number:
5
The given number 5 is not even number

2)
Please enter number

10
The given number 10 is even number


See This links also



Tribonacci Series
Floyds-Triangle   
Octal to Decimal






Sunday, May 4, 2014

Reverse the String in different ways


String is a sequence of  characters. It is a java object to store String type of values.String is a immutable class means if we create once String object with value, cannot be change its value. Any java programmer will attend interview,If interviewer asked 10 questions, in that one question is on String related. String is playing vital role in Java language.Recently one of my friend attend one interview, in that his interviewer asked question about String related.What's that question is "In how many ways we can reverse the String?". As per his java String knowledge he told like this "we can reverse the String in 3 different ways.By using String API we can reverse the String in two ways and without using String API we can reverse the String in two ways".He told like this then interviewer asked him explain that 3 ways .He explain all this 3 ways to interviewer.Then he selected in that interview without asking any further question by interviewer.why i should explain my friends interview process here is, how much Java String playing important role in Interviews.Now i will explain that 3 ways with examples.Please see below

1)Generally we can do reverse of String  by using String API method toCharArray(). we call this method on String object then it will return char Array.
                 String stringVar = "Hai how are you man";
            // Here we calling toCharArray() method on  String object  stringVar then arrayForOriginal           // contains array of characters of that String
                 char arrayForOriginal[] = stringVar.toCharArray();
                 int originalArrLen = arrayForOriginal.length;
                 char arrayForReverse[] = new char[originalArrLen];
                 int reverseIndex = 0;
                 for(int indexVal = originalArrLen - 1; indexVal  >= 0; indexVal--) {
                        arrayForReverse[ reverseIndex] =   arrayForOriginal[indexVal] ;
                         reverseIndex++;
                }
               System.out.println( "Reverse of original String is: "+arrayForReverse);  



Output:


         Reverse of original String is:  nam uoy era woh iah 



2)The second way to reverse the String, we can do this little bit different. Means we can perform this way using charAt() method String API. Here we get each character from String and store that character to Another array.After convert that array  to String.
              String stringVar = "Hai how are you man";
           /** Here we calling toCharArray() method on  String object  stringVar then arrayForOriginal          * contains array of characters of that String
         */
                

 int originalArrLen =  stringVar.length;
             String reverseString = "";
                 int reverseIndex = 0;
                for(int i = originalArrLen - 1;i >= 0;i--){
 reverseString  reverseString+stringVar.charAt(i);
}
               System.out.println( "Reverse of original String is: "+ reverseString);  

Output:
            
           Reverse of original String is:  nam uoy era woh iaH 

3) In this way we can do reverse of String without using String API. Means by using StringBuffer Class.Creating StringBuffer object as passing String value as argument to StringBuffer constructor. After calling reverse method of StringBuffer class on StringBuffer object.How we can do this programmatically, see below

           String originalVal = "What are you doing now";

           StringBuffer stringBufferVal = new StringBuffer(originalVal);
          System.out.prinln(stringBufferVal.reverse());
Output:
            
           Reverse of original String is:  nam uoy era woh iaH



See also this posts:


octal to decimal in java

add two numbers each number has more than 1000 numbers
prime number


Sunday, February 9, 2014

Prime Number


            
The Prime Number term is actually used in mathematics.  Definition of Prime Number is "The number Which is not divisible by any number except itself and 1". For example 2,3,5,7,11,........... Generally we can find a number is prime or not in mathematics but how we can find prime numbers in C,C++,Java,............etc.Now a days in most interviews,interviewer will asking one question that is "Write a program for given number is prime or not?". Recently one of my friend attend C language interview last two days back. He shared his interview experience with me. My friend said to me which type of questions they asked to him, from that discussion i am posting one important question that is "Write a program for given number is Prime or not"?. We can solve this type question in general way but when we attempting interview we can little bit different way. 

Program to find given number is  Prime Number  or not in C Language:
This is a basic program to find given number is prime or not.


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

int main(void){
      int a = 0;//this variable is used to store given number
      int count = 0;//this variable is used to know how many times given number is divisible.
      println("Enter a number: ");
      scanf("%d",&a);//taking entered number to a variable
      
      for(int i = 0;i <= a;i++){
          if(a%i == 0){
               count++;
          }
      }
      if(count == 2){
          printf("Given number %d is Prime Number",a);
     }


Output :

Enter a number : 19

Given number 19 is Prime Number



In another way, we can find the given number is prime or not.In Maths one short cut formula is available.The formula is If you want to find given number is prime or not.
Step 1:
           First we find the square root of given number.
           Ex: Given number is 19 . Square Root of 19 is 4.358898.
Step 2:
           If given number is divisible by less than or equal to 4. Means number is divisible by 1 or 2 or 3 or 4.
Step 3:
           Number is not divisible by 1 or 2 or 3 or 4 numbers.So 19 is Prime Number.



Now we can write the above steps convert to C Language.

#include<stdio.h>

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

int main(void){

   int inputNumber = 0;
   int count = 0;
   printf("Enter a number");
   scanf("%d", &inputNumber);
   
   int  sqrtValue = sqrt(inputNumber);
   for(int i = 2;i <= sqrtValue;i++){
        if(inputNumber%i == 0){
         count++;
        }
   }
   if(count == 1){
     printf("Given number %d is Prime Number",inputNumber);
   }else{
     printf("Given number %d is not a Prime Number",inputNumber);
   }
   return 0;
}


In above program, for loop is started from 2 value not 1 because Every number is divisible by 1.That's why for loop is start from 2.


See this related posts:

write program to sort integer number
How many ways are there to register jdbc driver
Floyd's triangle

Thursday, December 26, 2013

Addition of numbers each number has more than 1000 digits in java

//Author ramraj.vasavi
package com.rrv;
import java.util.Scanner;
class Add
{
    public static void main(String[] args)
    {
        Scanner scannerInput=new Scanner(System.in);
        System.out.println("Enter your First Number");
        String first=scannerInput.next();
        System.out.println("Enter your Second Number");
        String second=scannerInput.next();
        int[] num1=convertInt(first);
        int[] num2=convertInt(second);
        int fLength=num1.length;
        int sLength=num2.length;
        if(first.equals("0")&&second.equals("0"))
        {
         System.out.println("Addition of two Numbers is: "+"0");
        }
        else if(first.equals("0"))
        {
            
          System.out.println("Addition of two Numbers is: "+second);
        }
        else if(second.equals("0"))
        {
          System.out.println("Addition of two Numbers is: "+first);
        }
        else{
           if(fLength>sLength)
             Add.add(num1,num2);
           else
             Add.add(num2,num1);
        } 
        
    }
    public static void add(int[] oparend1,int[] oparend2)
    {
        int[] result=new int[oparend1.length];
        int op2Length=oparend2.length-1;
        int op1Length=oparend1.length-1;
        int sum=0;
        for(int index=0;index<=op1Length;index++)
        {
            if(index>=oparend2.length)
             sum=oparend1[op1Length-index]+sum;
            else
                 sum+=oparend1[op1Length-index]+oparend2[op2Length-index];
        int digit=sum%10;        
         sum=sum/10;
         result[index]=digit;
        }
        String output="";
        for(int index=result.length-1;index>=0;index--)
        {
                        output=output+result[index];
         }
        System.out.println("Addition of two numbers is: "+output);
    }
   public static int[] convertInt(String str){
       int[] arr=new int[str.length()];
      for(int index=0;index<str.length();index++)
       {
           arr[index]=(int)str.charAt(index)-48;
       }
     return arr;
   }
}

Output of Addition.java:

Enter your First number: 54832415789132118

Enter your Second Number: 9213849898

Addition of Two numbers is: 54832425002982016

How many ways to swap to numbers without using third variable in java

Swapping of two numbers program is a frequently asking question in interviews.If we want to swap to two numbers ,We will use third variable. Let's see simple example below

public static void swappingNumbers(num1, num2) {
        var tempVariable = num1;
        num1 = num2;
        num2 = tempVariable;
}

Like above we will do. But we can do this program in three ways without using third variable.

1) In first way, we add first and second numbers then store result into first variable. After subtract second value from first result, store that result into second variable.At last, subtract second result from first result then store this result into first variable.For more clarification see  below program

    public static void swappingNumType1(num1, num2)
     {
          num1 = num1 + num2;
          num2 = num1 - num2;
          num1 = num1 - num2;
          System.out.println("num1 = "+num1+"  num2 = "+num2);
     }
    
2)
              In second way,we multiply first and second numbers then store this  result into first variable. After devide first result with second value,store second result into second variable. At last, divide first result with second result then store result into first variable. For more clarification see below program

     public static void swappingNumType1(num1, num2)
     {
          num1 = num1 * num2;
          num2 = num1 / num2;
          num1 = num1 / num2;
          System.out.println("num1 = "+num1+"  num2 = "+num2);
     }

3) In third way,we  will add two numbers by using ^(XOR) operator.

     public static void swappingNumType1(num1, num2)

     {
          num1 = num1 ^ num2;
          num2 = num1 ^ num2;
          num1 = num1 ^ num2;
          System.out.println("num1 = "+num1+"  num2 = "+num2);
     }

We will also swap two Strings without using third variable. It is possible by using subString() method of String API.

     public static void main(String[] args)
{
String a = "rrv";
String b = "techdiamod";
a = a+b;
b=a.substring(0,a.length()-b.length());
a=a.substring(b.length());
System.out.println("Swappng Strings are "+a+"    "+b);

    }


         
  

Display Stars using javascript

a. Take a positive integer value from the respondent as below fig. and Display Star Diamond.
b. Validate above form field
c. ON VALIDATION DISPLAY PROPER USER FRIENDLY MESSAGE TO USER.
d. Try to design a good looking html page with proper alignment..
e. You are only allowed to use HTML for design the page and JavaScript for scripting logic.



<html>
<head>
<script type="text/javascript">
function display(){
var reg=/^[0-9]$/;
var content = document.getElementById("top").innerHTML;
var divText="<br><fieldset style='background-color:green;color: #123abc;width: 400px;'><legend>"+"Star Diamond"+"</legend><fieldset style='background-color:yellow;color: #123546;width: 75px;'>";
var input=document.getElementById("tex").value*1;
var space=input-2;
var line=(input+1)/2;
;
if(input==""){
alert("Please enter Number");
return false;
}
if((input%2)==0)
{
alert("Please enter Number");
return false;
}
for(var i=0; i<line;i++)
{
for (var c = 1 ; c < space; c++ )
divText=divText+"&nbsp";
space--;
for (var d = 1 ; d <=2*i+1 ; d++ )
divText=divText+"*";
divText=divText+"<br>";
}
var down=(input-1)/2;
var spa=1;
for(var r=down; r>0; r--)
{
for(var sp=spa; sp>=1; sp--)
divText=divText+"&nbsp";
spa++;
for(var m=1; m<=2*r-1; m++)
divText=divText+"*";
divText=divText+"<br>";
}
divText=divText+"</fieldset>";
content=content+divText;
document.getElementById("top").innerHTML=content;
return true;
}
</script>
</head>
<body><center><form id="1">
<div id="top">
<fieldset style="background-color:orange;color: #123abc; width: 400px;">
<legend style="background-color:green;color: #ff0000; font-family: verdana; font-size: 14pt;">DISPLAY</legend>
<div>Enter Number you want:<input type="textid="texvalue=""><input type="buttonid="disvalue="Displayonclick="return display()"></div>
</fieldset>
</div>
</form></center>
</body>
</html>

Pan Digit Number program

/** Program Name PanDigit.java
     Author :RamRajVasavi

*/
package blog.rrvTechDiamond;
import java.util.Scanner;
public class PanDigit {
             //Writing codefor main() method
public static void main(String[] args) {
//creating object for Scanner Class
Scanner scannerInput=new Scanner(System.in);
                          //Printing Message
System.out.println("Enter No of Digit PanNumber want");
                           //Taking input from endUser
int noOfDigits=scannerInput.nextInt();
                          //Declaring variables
                          boolean check=true;
int panIndex;
int endNo=1;
int index=1;
int integer=10;
int panIf=0;
//creating start and end range
while(index<=noOfDigits)
{
endNo=endNo*integer;
index++;
}
int limit=endNo-1;
int startNo=(endNo/10)+1;
endNo=endNo-(endNo/10)*(10-(noOfDigits+1));
panIndex=startNo;
                          //checking the number is panDigit or not
while(panIndex<=endNo){
                                        //calling panNumber() method
check=panNumber(panIndex,noOfDigits);
if(check==true){
panIf++;
System.out.println(panIndex+" is PanDigit Number");
}
else{
    System.out.println(panIndex+" is not PanDigit Number");
}
panIndex++;
}
System.out.println("The PanDigitNumber from "+startNo+"---"+limit+" is: "+panIf);
}
             //Writing code for panNumber()method 
public static boolean panNumber(int panIndex,int noOfDigits){
                          //creating array object
int arr[]=new int[noOfDigits];
int index=-1;
                          //Number is convert to array
while(panIndex>0){
index++;
int digit=panIndex%10;
arr[index]=digit;
panIndex=panIndex/10;
}
                          //checking for duplicate numbers
for(int digitIndex=0;digitIndex<noOfDigits;digitIndex++){
for(int lowIndex=0;lowIndex<noOfDigits;lowIndex++){
if((digitIndex!=lowIndex)&&(arr[digitIndex]==arr[lowIndex]))
return false;
if(arr[digitIndex]==0)
return false;
}
}
int count=0;
                          //Number contains digits less than that noOfDigits we entered
for(int idex=0;idex<noOfDigits;idex++){
if(arr[idex]<=noOfDigits)
count++;
}
if(count==noOfDigits)
return true;
return false;
}

}


Output:

D:\>java PanDigit
Enter No of Digit PanNumber want
5

10001 is not PanDigit Number
10002 is not PanDigit Number
10003 is not PanDigit Number
10004 is not PanDigit Number
10005 is not PanDigit Number
10006 is not PanDigit Number
10007 is not PanDigit Number
10008 is not PanDigit Number
10009 is not PanDigit Number
10010 is not PanDigit Number
10011 is not PanDigit Number
10012 is not PanDigit Number
10013 is not PanDigit Number
----
----
----
----
----