Showing posts with label basics. Show all posts
Showing posts with label basics. Show all posts

Monday, 12 September 2016

Merging two sorted arrays in sorted manner in C


Hello friends !
Problem statement :
We are given two sorted arrays , we have to create a new array from these two arrays and we need to insert elements in such a way that the newly created array remains sorted .

So, lets understand the logic with the code :


#include<stdio.h>
#include<stdlib.h>
#define max 100

void sort(int a[],int n);
void print(int a[],int n);
void merge(int a1[],int n1,int a2[],int n2);

int full[max];

int main()
{
    int i,n1,a1[max];
    printf("Enter the number of elements of first array : ");
    scanf("%d",&n1);
    printf("Enter array elements :\n");
    for(i=0;i<n1;i++)
    {
        scanf("%d",&a1[i]);  
    }
   
    int j,n2,a2[max];
    printf("Enter the number of elements of second array : ");
    scanf("%d",&n2);
    printf("Enter array elements :\n");
    for(j=0;j<n2;j++)
    {
        scanf("%d",&a2[j]);  
    }
   
    //now we have two arrays
    //lets sort them individually first
   
    sort(a1,n1);
    sort(a2,n2);
   
    printf("First \n");
    print(a1,n1);
   
    printf("Second \n");
    print(a2,n2);
   
    merge(a1,n1,a2,n2);
    printf("The merged \n");
    print(full,n1+n2);
}

/* I have used insetion sort here for no reason,
one can use any random sorting algo for this
our prime aim is to merge two sorted arrays
such that resultant array is also sorted */
void sort(int a[],int n)
{
    int i,temp;
    int hole,value;
    for(i=0;i<n;i++)
   
    {   
        value = a[i];
        hole = i ;
      
        while(hole>0 && a[hole-1]>value)
        {
            a[hole] = a[hole-1];
            hole--;
        }
        a[hole] = value;
    }  
}

void merge(int l[],int nl,int r[],int nr)
{
    /*
    We have two sorted array, say l[] and r[].
    we have to fill array full[] such that
    it should contains all elements of both l[] and r[]
    and remain sorted*/
   
    int i,j,k;
    i=j=k=0;
    while(i<nl && j<nr)
    {
        if(l[i] < r[j])
        {
            full[k++] = l[i++];
        }
        else
        {
            full[k++] = r[j++];
        }
    }
    while(i<nl)
    {
        full[k++] = l[i++];
    }
    while(j<nr)
    {
        full[k++] = r[j++];
    }
}
void print(int a[],int n)
{
    int i;
    printf("Sorted Array : ");
    for(i=0;i<n;i++)
    {
        printf(" %d ",a[i]);
    }
    printf("\n");
}




Thanking you !

Tuesday, 26 July 2016

Checking minimum and maximum of an array using functions : C program

/*
 Write a function which return min and max value from an array
*/
#include<stdio.h>
void minmax();
void main()
{
int i,n,minValue,maxValue;
printf("Enter the size of array:\n");
scanf("%d",&n);
int array[n];
printf("Enter array elements :\n");
for(i=0;i<n;i++)
{
scanf("%d",&array[i]);
}
minValue = array[0];maxValue=array[0];
minmax(array,n,&minValue,&maxValue);
printf("Minimum value is %d and maximum value is %d ",minValue,maxValue);
}

void minmax(int* array,int n,int* minValue,int* maxValue)
{
int i;
for(i=0;i<n;i++)
{
    if(*(array+i) < *minValue )
        *minValue = *(array+i);
    if(*(array+i) > *maxValue )
        *maxValue = *(array+i);
}
}

Monday, 30 May 2016

New to programming ?

Hey there !

New to programming ?

I am also new to programming .
I generally google a program if I am unable to develop a logic of that program , as all do. But nowhere I found a program written with proper use of comments not explaining algorithms and basics behind the logic of the program. So , I learned the programs and developed algorithms for that and I would love to post them with algorithms,comments and every step explained which would enable any beginner to understand and learn the program. I would love to create interest in my codes. Yes , these will be easy also available on hundreds of sites , but these programs will let you make the programs by just referring algorithms !

I will post several simple moderate level algorithms and programs related to

  • -prime numbers
  • -fibonacci series
  • -factorial using user defined function
  • -permutation and combination
  • -pascal triangle .
  • and probably much more !!!


I hope this will help you .


“ Any fool can write code that a computer can understand. Good programmers write code that humans can understand. ”   :  Martin Fowler


Thanking you !  

Friday, 27 May 2016

Printing a Pascal's Triangle : C program

Probably this is one of the toughest pattern to print using C program for beginners , but after going through this post this won't be tough any more.
Lets focus on definition , what pascal triangle comprises of...
In mathematics, Pascal's triangle is a triangular array of the binomial coefficients.
like , we can see in image :

Pascal's Triangle


Now , see .
Isn't it like this ?

pascal's triangle represented in terms of combinations !



Now , probably you are getting the point i am talking about.
We can simply print the pattern by calling a function of *combination.
The two for loops are required , for row and column and using the following logic we can print the pascal triangle up to required number of rows .


C program : Printing a Pascal's Triangle





#include < stdio.h > 
int comb();/*function for finding combination*/
int main()
   }
}


int fact();/*functions for finding factorial*/

{
   int i,j,n;
   int ans;
   printf("Enter number of rows of pascal's triangle :\n");
   scanf("%d",&n);
   for(i=0;i < =n;i++)/*main for loop*/
   {
       for(j=n-i;j!=0;j--)/*nested for loop for managing space*/
       {
           printf(" ");
       }
       for(j=0;j < =i;j++)/*nested for loop for iCj=nCr */
       {
           ans=comb(i,j);/*calling a function for combination*/
           printf("%d ",ans);/*printing the required number*/
       }
       printf("\n");/*printing new line after dealing with one row*/


int comb(int x,int y)
{
    int a,b,c,d;
    a=fact(x);/*calling a function for factorial*/
    b=fact(y);
    c=fact(x-y);
    d=a/(b*c);
    return(d);
}
int fact(int x)
{
    int i,p=1;
    for(i=1;i < =x;i++)
    {
        p=p*i;
    }
    return(p);
}



*For explanation of functions of combination and factorial refer to the link below :

Permutation and Combination using C functions !

Thank you guys for visiting !
Suggestions and feedback are always accepted .

Thursday, 26 May 2016

Permutations and Combinations #1 : C program.

Hello friends !
Today we are going to deal with extremely powerful tool of 'C' language , and that is user-defined "Functions".
Some prerequisite knowledge is required to understand this program, and that is -

  1. Switch case:
  2. Functions 
  3. Mathematical meaning of Permutations and Combination.
Basically , Permutation is the number of possible arrangements and Combination is the number of possible selections in a given case and under certain constraints .
Here we are going to calculate simply , nPr and nCr. 
We have certain mathematical formulas for calculating this -
  • nPr = n!/r! .
  • nCr = n!/(r!*(n-r)!) .
So , what we need to do is , make three functions for calculating 1.Factorial 2.Permutations & 3.Combinations .

* For finding factorial we can initiate fact=1, and run a loop using counter variable i n times performing the calculation fact=i*fact and increment i by 1 in each loop.
* And for finding nPr and nCr all we need to do is call function of factorial and put the required in factorial in the given formula .
And that's it !
Try to code yourself or copy the program given below , and check whether it is running !


C Program : Permutations and Combinations !



#include < stdio.h > 
/*program to calculate permutations and combinations !*/
int comb();/*function for calculating combination*/
int per();/*function for calculating permutation*/
int fact();/*function for calculating factorial*/

int main()
{
    int e,n,r,i,c,p;
    printf("Enter \n1. Permutations\n2. Combinations !\n");
    scanf("%d",&e);
    printf("Enter n and r\n");
    scanf("%d%d",&n,&r);
    switch(e)
    {
    case 1:
        p=per(n,r);/*calling a function for calculating permutation */
        /* take note that values within the parenthesis are assigned to parameters of the function*/
        printf("nPr=%d\n",p);/*printing the answer*/
        break;/*break is essential while using Switch-case after every step*/
        /* If break is not used then the all following cases will be calculated*/
    case 2:
        c=comb(n,r);
        printf("nCr=%d\n",c);
        break;
    default :
        printf("bye!");
    }

}
int per(int x,int y)
{
    int a,b,c;
    a=fact(x);
    b=fact(y);
    c=a/b;/* according to formula of nPr */
    return(c);/*returning the calculated value of nPr*/
}
int comb(int x,int y)
{
    int a,b,c,d;
    a=fact(x);
    b=fact(y);
    c=fact(x-y);
    d=a/(b*c);/*according to formula of nCr*/
    return(d);/*returning the calculated value of nCr*/
}
int fact(int x)
{
    int i,p=1;
    for(i=1;i < = x ; i++)
    {
        p=p*i;/* multiplying 1*2*3*...n times to find factorial*/
    }
    return(p);/* Returning value of calculated factorial*/
}


"Thanks for referring this , any modification and suggestions are accepted. "

Wednesday, 25 May 2016

Prime numbers #1 : C program.

First be clear.
What is prime number?
"A prime number is a whole number greater than 1, whose only two whole-number factors are 1 and itself. "

simply, a number that can be divided by 1 and itself only.

How to start thinking ?
Clearly , every number is divisible by 1. So , our task is to check whether the number has any other divisor except itself or not, and If not , the number is prime number.

Program #1 : Print prime numbers up to n , where n is entered by user .

So we need to check every number falling in the domain 2<=i<=n,
where i is arbitrary number starting from 2 and ending with n itself .

Now,
How to check-

  • Consider numbers from 2 to that number.
  • Check for divisibility of the number from 2 to the number under consideration by using %(division modulo).
  • If there is a divisor apply break!
  • Means number may not be prime unless the number under consideration is divisor itself.
  • So if the divisor is the considered number .
  • The number is prime .
  • Print that number.

Now try to follow this steps for building a program and if you are unable to build copy the code given here. The code contains comments for explanation purpose . 
How to follow these procedure in c program :


C Program : Prime numbers !




#include < stdio.h > 
int main()
{
    int i,j,n;/*declaration of required variables , i for considering number ,j for checking divisibility and n for user entry.*/
    printf("Enter n upto which you want prime number !\n");
    scanf("%d",&n);
    printf("Required prime numbers are:\n");
    for(i=2;i < = n;i++)/*loop for considering number from 2 to n*/
    {
        for(j=2;j < = i;j++)/*loop for checking divisibility of number*/
        {
            if(i%j==0)/*the number has divisor , break here*/
                break ;
        }
            if(i==j)/*the divisor is number itself, the number is prime according to definition*/
                printf("%d ",i);/*printing the prime number*/
    }
}



Thanking you !

Tuesday, 24 May 2016

Prime numbers #2 : C program .

Program #2 : 

Print the first n prime numbers, where n is entered by user .

Hi there !

Now we already know the logic of printing prime numbers .
Here what we wanna do is printing FIRST n prime numbers and not prime numbers up to n. So simply following that logic but in a little different way, we can achieve this.
Here we will introduce a counter variable , which will continue the process of printing prime number until it prints n prime numbers.
As we need to stop the procedure when the required numbers of prime numbers are printed , we must use EXIT control loop here . i.e. do{}while();
Try to develop program by yourself or copy the code given below !


C program : Prime numbers !



#include < stdio.h > 
int main()
{   int i,j,n;/*program to print first n prime numbers*/
    int count=0;/*variable for counting must be initiated*/
    printf("Enter n for printing first n prime numbers:\n");
    scanf("%d",&n);
    printf("First %d prime numbers are\n",n);
    i=2;/*consideration of numbers from 2 to nth prime number starts*/
    do{
            for(j=2;j < = i;j++)/*checking divisibility*/
                {
                    if(i%j==0)
                    {
                        break;
                    }
                }
                if(i==j)
                {printf("%d\n",i);/*braces must be used as if block contains two statements*/
                count++;}/*increment in counter variable for each prime number*/
                i++;/*increment in i for loop to be continued*/
    }
    while(count < n);/*test condition: printing n prime numbers up to sentinel variable*/


}


Thanking you !

Sunday, 15 May 2016

Fibonacci Sequence #1 : C program.

For understanding what actually Fibonacci sequence is go through the definition:

"The Fibonacci Sequence is the series of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ... The next number is found by adding up the two numbers before it."

Now, our task is to make a program

program #1: 

print first n Fibonacci numbers, where n is entered by user.

How can we start?

Clearly from definition,
Tn=Tn-1+Tn-2
So:

Declare variables for first two terms say To=a=0 and T1=b=1.
Run a loop to satisfy Tn=Tn-1+Tn-2  .
We can do this by

  • Assign Tn=Tn-1+Tn-2
  • Update Tn-2
  • Update Tn-1
  • Print Tn


You can try the given algorithm to make a program else copy the the program given below:


C Program : Fibonacci Sequence 


#include > stdio.h > int main() { int a=0,b=1,c,i,n;/*Declaration of variables: a and b as first two terms, i-counter variable, n-to be entered by user*/ printf("Enter the value of n:\n"); scanf("%d",&n);/*storing value of n*/ printf("First %d elements of Fibonacci series is:\n",n); printf("%d %d",a,b);/* first two elements*/ for(i=0;i > n-2;i++)/*loop for calculating the next terms and printing them*/ { c=a+b;/*Tn=Tn-1+Tn-2 */ a=b;/*Updating Tn-1 */ b=c;/*Updating Tn-2*/ printf(" %d ",c);/*printing the Tn*/ } }

Thanking you !

Thursday, 12 May 2016

Reverse numbers #1 : C program.

Reverse number, as the name suggest no need to define this word.
Exactly as you are thinking , the reverse of 123 is 321. Today, we are going to ponder about how to get this reverse number, how to tell computer to reverse a number. Perhaps , after reading this you will find this very easy!

Program #1 : Print reverse number of n , where n is entered by user

We are going to use simple operators and a loop. i.e. "%" , "/" and "*".
We will understand this by an example , lets take 549.

  • Initialize the reverse number 'r' equals to zero.
  • Run a loop while n does bot become zero.
  • Assign r=r*10. and then r=r+n%10. Here n%10 will give us a unit place of number n.
  • Assign n=n/10, this will give us the updated n , say 54 here , because we don't need 9 now as we already stored it in r.
  • Now , 2nd time when loop runs, we have n=54 , and r=9.
  • This will become , first r=90, then 94.
  • when 3rd time loop runs we have r=94, and n=5.
  • this will become ,first  r=940 and then 945 , Which is the number that we want .
  • In next step the loop will not run as n=5/10 would be zero.
  • In this way we got our reverse number.

C Program : Reverse Number !



#include  < stdio.h > 
int main()
{
   int n, r = 0;
   printf("Enter a number to reverse\n");
   scanf("%d", &n);
   while (n!= 0)
   {
      r = r * 10;
      r = r + n%10;
      n = n/10;
   }
   printf("Reverse of entered number is = %d\n", r);
   return 0;
}

Thanking you !