Thursday, February 26, 2015

Java Basics

What is "out" on System.out.println() ?

In the System class "out" is an static final variable of class type i.e. it's an object of the "PrintStream" class. And this printsream class contains a definition of a public method called "println()".

here is the actual representation of the classes:

//the System class belongs to java.lang package
class System {
  public static final PrintStream out;
  //...
}

//the Prinstream class belongs to java.io package
class PrintStream{
public void println();
//...
}

Wednesday, February 25, 2015

Pair of Numbers

C program to find presence of  pair of elements in array whose sum is equal to a given number.

#include<stdio.h>
int cmp(const void *a,const void *b)
{
return (*(int*)a-*(int*)b);
}
int main()
{
int n,i,x,j,flag=0;
printf("Enter the no. of elements in array:");
scanf("%d",&n);
int a[n];
printf("Enter the elements of array:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the sum of Numbers:"); 
scanf("%d",&x);
qsort(a,n,sizeof(int),cmp);
i=0;j=n-1;
while(i<j)
{
if((a[i]+a[j])==x)
{
flag=1;
break;
}
else if((a[i]+a[j])>x) j--;
else if((a[i]+a[j])<x) i++;
}
if(flag)
printf("\nPresent");
else
printf("\nNot Present");
return 0;
}

Distinct Characters

C program to find number of distinct characters in a string.

#include<stdio.h>
int main()
{
char a[100001];
unsigned int b[26],i=0,c=0;
memset(b,0,26*sizeof(unsigned int));
printf("Enter the String: ");
scanf("%s",a);
while(a[i]!='\0')
{
b[a[i]-'a']++;
i++;
}
for(i=0;i<26;i++)
{
if(b[i]!=0) c++;
}
printf("There are total %u characters in string.\n",c);
return 0;
}

Tuesday, February 24, 2015

Large Factorials

 C program to find factorial of a number N <= 100 .

#include<stdio.h>
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int a[200],m=0,i,k,n,temp=0;
    scanf("%d",&n);
        a[0]=1;
        m=1;
        while(n>1)
        {
            for(i=0;i<m;i++)
            {
                k=((a[i]*n)+temp);
                a[i]=k%10;
                temp=k/10;
            }
            while(temp>0)
            {
                a[m++]=temp%10;
                temp/=10;
            }
            n--;
        }
        for(i=m-1;i>=0;i--)
            printf("%d",a[i]);
        printf("\n");
    }
    return 0;
}