How to Declare Union in C ? | Using Union in C | Union Example in C | C Program to Explain use of union

How to Declare Union in C ? | Using Union in C | Union Example in C | C Program to Explain use of union



union tag
{
union_member1;
union_member2;
union_member3;
..
..
..
union_memberN;
}instance;





    Union Members that compose a union , all share the same storage area within the computers memory
    Each member within a structure is assigned its own unique storage area
    Thus unions are used to observe memory.
    Unions are useful for application involving multiple members , where values need not be assigned to all the members at any one time.

Related Links :

C Program to perform Stack Operations Using Pointer | C Language Stack Operation with Pointers

C Program to perform Stack Operations Using Pointer | C Language Stack Operation with Pointers | Pointers and stack operation in C



#include
#include
#include
#define MAX 50

int size;

/* Defining the stack structure */
struct stack
{
    int AR[MAX];
    int top;
};

/* Initializing the stack(i.e., top=-1)   */
void init_stk(struct stack *st)
{
    st->top=-1;
}

/* Entering the elements into stack */
void push (struct stack *st,int num)
{
    if(st->top == size-1)
    {
    printf("\nStack overflow(i.e., stack full).");
    return;
    }
    
    st->top++;
    st->AR[st->top] = num;
}

//Deleting an element from the stack.
int pop(struct stack *st)
{
    int num;
    if(st->top == -1)
    {
    printf("\nStack underflow(i.e., stack empty).");
    return NULL;
    }
    
    num=st->AR[st->top];
    st->top--;
    return num;
}
void display(struct stack *st)
{
    int i;
    for(i=st->top;i>=0;i--)
        printf("\n%d",st->AR[i]);
}
void main()
{
    int ele,opt,val;
    struct stack ptr;
    clrscr();
    init_stk(&ptr);
    printf("\nEnter Stack Size :");
    scanf("%d",&size);
    while(1)
    {
        printf("\n\n\tSTACK PRIMITIVE OPERATIONS");
        printf("\n1.PUSH");
        printf("\n2.POP");
        printf("\n3.DISPLAY");
        printf("\n4.QUIT");
        printf("\n");
        printf("\nEnter your option : ");
        scanf("%d",&opt);
        switch(opt)
        {
            case 1:
                printf("\nEnter the element into stack:");
                scanf("%d",&val);
                push(&ptr,val);
                break;
            case 2:
                ele=pop(&ptr);
                printf("\nThe element popped from stack is : %d",ele);
                break;
            case 3:
                printf("\nThe current stack elements are:");
                display(&ptr);
                break;
            case 4:
                getch();
                exit(0);
            default:
                printf("\nEnter correct option!Try again.");
        }
    }
}



Related Links :

C Program Add Two Numbers Using Pointer | Addition of Numbers using Pointers in C

C Program Add Two Numbers Using Pointer | Addition of Numbers using Pointers in C | C Language Pointers Addition of numbers



#include
int main()
{
int *ptr1,*ptr2;
int num;

printf("\nEnter two numbers : ");
scanf("%d %d",ptr1,ptr2);

num = *ptr1 + *ptr2;

printf("Sum = %d",num);
return(0);
}


O/P :
Enter two numbers : 2 3
Sum = 5

Related Links :

C Program to calculate sum of the array elements using pointers | Sum Elements using pointers in array | Addition of array elements using pointers in C

C Program to calculate sum of the array elements using pointers | Sum Elements using pointers in array | Addition of array elements using pointers in C



#include
#include
void main()
{
 int a[10];
 int i,sum=0;
 int *ptr;
 
 printf("Enter 10 elements:\n");
 
 for(i=0;i<10;i++)
    scanf("%d",&a[i]);
    
 ptr = a;           /* a=&a[0] */

 for(i=0;i<10;i++)
    {
    sum = sum + *ptr;    //*p=content pointed by 'ptr'
    ptr++;
    }
    
 printf("The sum of array elements is %d",sum);
}



Related Links :

Program to implement stack with its operations using pointers in C | C Program to show implement stack with its operations using pointers

Program to implement stack with its operations using pointers in C | C Program to show implement stack with its operations using pointers | implement stack with its operations using pointers in C Language




#include
#include
#include
#define MAX 50

int size;

/* Defining the stack structure */
struct stack
{
    int AR[MAX];
    int top;
};

/* Initializing the stack(i.e., top=-1)   */
void init_stk(struct stack *st)
{
    st->top=-1;
}

/* Entering the elements into stack */
void push (struct stack *st,int num)
{
    if(st->top == size-1)
    {
    printf("\nStack overflow(i.e., stack full).");
    return;
    }
    
    st->top++;
    st->AR[st->top] = num;
}

//Deleting an element from the stack.
int pop(struct stack *st)
{
    int num;
    if(st->top == -1)
    {
    printf("\nStack underflow(i.e., stack empty).");
    return NULL;
    }
    
    num=st->AR[st->top];
    st->top--;
    return num;
}
void display(struct stack *st)
{
    int i;
    for(i=st->top;i>=0;i--)
        printf("\n%d",st->AR[i]);
}
void main()
{
    int ele,opt,val;
    struct stack ptr;
    clrscr();
    init_stk(&ptr);
    printf("\nEnter Stack Size :");
    scanf("%d",&size);
    while(1)
    {
        printf("\n\n\tSTACK PRIMITIVE OPERATIONS");
        printf("\n1.PUSH");
        printf("\n2.POP");
        printf("\n3.DISPLAY");
        printf("\n4.QUIT");
        printf("\n");
        printf("\nEnter your option : ");
        scanf("%d",&opt);
        switch(opt)
        {
            case 1:
                printf("\nEnter the element into stack:");
                scanf("%d",&val);
                push(&ptr,val);
                break;
            case 2:
                ele=pop(&ptr);
                printf("\nThe element popped from stack is : %d",ele);
                break;
            case 3:
                printf("\nThe current stack elements are:");
                display(&ptr);
                break;
            case 4:
                getch();
                exit(0);
            default:
                printf("\nEnter correct option!Try again.");
        }
    }
}

Related Links :

C Programming Memory Representation arrays | Multidimensional Array Memory Representation

Memory Representation of Multidimensional Array in C Language | C Programming Memory Representation  arrays | Multidimensional Array Memory Representation

 

Memory Representation
  • 2-D arrays are Stored in contiguous memory location row wise.
  • 3 X 3 Array is shown below in the first Diagram.
  • Consider 3×3 Array is stored in Contiguous memory location which starts from 4000 .
  • Array element a[0][0] will be stored at address 4000 again a[0][1] will be stored to next memory location i.e Elements stored row-wise
  • After Elements of First Row are stored in appropriate memory location , elements of next row get their corresponding mem. locations.

Basic Memory Address Calculation :

a[0][1] = a[0][0] + Size of Data Type
ElementMemory Location
a[0][0]4000
a[0][1]4002
a[0][2]4004
a[1][0]4006
a[1][1]4008
a[1][2]4010
a[2][0]4012
a[2][1]4014
a[2][2]4016

Related Links :

C program to check word is palindrome or not | C Program to find word is palindrome or not

C program to check word is palindrome or not | C Program to find word is palindrome or not





#include
#include
main()
{
    int i,j=0,k;
    char a[20];
    printf("Enter a word to check whether its a palindrome.\n");
    scanf("%s",a);
    k=strlen(a);
    for (i=0;i<k/2;i++)
    {
        if(a[i]==a[k-i-1])
        ;                  //empty statement.
        else
         {
          j++;
          break;
         }
    }
    if(j>0)
    printf("The word is not palindrome .\n");
    else
    printf("The word is palindrome .\n");
    getch();
}

Related Links :

ASCII code of any character in C | C Program to Print ASCII code of Entered character| ASCII of any character in C

ASCII code of any character in C | C Program to Print ASCII code of Entered character| ASCII of any character in C





#include
#include
int main()
{
    char i;
    printf("Enter the character to get its ASCII code.\n");
    scanf("%c",&i);
    printf("\nASCII code of `%c` is %d\n\n",i,i);
    printf("\n");
    return 0;
}

Related Links :

matrix multiplication in C Language | C Program to show matrix multiplication | matrix multiplication assignment in C

matrix multiplication in C Language | C Program to show matrix multiplication | matrix multiplication assignment in C | Multiplication of matrix in C programming





#include
main()
{
    int j,i,k,m1,n1,m2,n2;
    int A[20][25],B[20][25],mul[20][25];         //declaration of 2 dimensional array
    printf("This is a program to get multiplication of two matrices A nad B\n\n");
    printf("Enter the rows in mat A..\n");
    scanf("%d",&m1);
    printf("Enter the columns in mat A..\n");
    scanf("%d",&n1);
    printf("Now keep on entering matrix elements.\n\n");
    for (i=0;i<m1;i++)
    {
        for (j=0;j<n1;j++)
        {
            printf("A%d%d=",i+1,j+1);
            scanf("%d",&k);
            A[i][j]=k;
        }
    }
   
    printf("\nEnter the rows in mat B..\n");
    scanf("%d",&m2);
    if(n1!=m2)
    {
        printf("\n\nDimension error.\nCan not multiply\nexiting...\n");
        exit(0);
    }
    printf("Enter the columns in mat B..\n");
    scanf("%d",&n2);
    printf("Now keep on entering matrix elements.\n\n");
    for (i=0;i<m2;i++)
    {
        for (j=0;j<n2;j++)
        {
            printf("B%d%d=",i+1,j+1);
            scanf("%d",&k);
            B[i][j]=k;
        }
    }
   
    printf("\n\nMatrix A is\n\n");
    for (i=0;i<m1;i++)
    {
        for (j=0;j<n1;j++)
        {
            printf ("%d ",A[i][j]);
        }
    putchar('\n');
    }
   
    printf("\n\nMatrix B is\n\n");
    for (i=0;i<m2;i++)
    {
        for (j=0;j<n2;j++)
        {
            printf ("%d ",B[i][j]);
        }
    putchar('\n');
    }
   
   
   
    for (i=0;i<m1;i++)            //initialisation of mat mul
    {
        for (j=0;j<n2;j++)
        {
             mul[i][j]=0;
        }
    }
   
   
    for (i=0;i<m1;i++)            //multiplication part
    {
        for (j=0;j<n2;j++)
        {
            for (k=0;k<n1;k++)
            {
                mul[i][j]+=A[i][k]*B[k][j];
            }
        }
    }
   
   
    printf("\n\nThe multiplied matrix is\n\n");
    for (i=0;i<m1;i++)
    {
        for (j=0;j<n2;j++)
        {
            printf ("%d ",mul[i][j]);
        }
    putchar('\n');
    }
    getchar();
}

Related Links :

C Program to print Fibonacci series | printing Fibonacci series in C Language | C Assignment to create Fibonacci series

C Program to print Fibonacci series | printing Fibonacci series in C Language | C Assignment to create Fibonacci series | Fibonacci series Logic in C Language




#include
main()
{
    int i=0,j=1,k=1,m=1,n;
    printf("Enter the number of terms.");
    scanf("%d",&n);
    printf("\n term no. \t value\n");
    printf("%d\t\t%d\n",m,k);
        for(m=1;m<n;)
        {
            k=i+j;
            printf("%d\t\t%d\n",++m,k);
            i=j;
            j=k;
        }
    printf("\n\n");
}

Related Links :

Equilateral star triangle in C | C Program to Create Equilateral Triangle of stars | Equilateral Triangle of star in C Programming | C Program to print Equilateral Triangle of Asterisk

Equilateral star triangle in C | C Program to Create Equilateral Triangle of stars | Equilateral Triangle of star in C Programming | C Program to print Equilateral Triangle of Asterisk





#include
main()
{
    int j,i,k,l;
    char c;
    do
    {
        printf("Enter the number of stars in the base..");
        scanf("%d",&k);
        for (i=1;i<=k;i++)
        {
            for(l=0;l<(k-i);l++)
                printf(" ");
            for (j=0;j<i;j++)
                printf ("* ");
            printf("\n");
        }
        printf("\n Enter y to try more...press any other key exit...\t");
    c=getchar();
    c=getchar();
    }
    while(c=='y');
}

Related Links :

C Program to print Pascal's triangle | Pascal's triangle in C | C Language to create Pascal's triangle | Pascal's triangle Logic in C language

C Program to print Pascal's triangle | Pascal's triangle in C | C Language to create Pascal's triangle | Pascal's triangle Logic in C language | Concept of creating Pascal's triangle in C Programming





#include
main()
{
    int i,j,k[50],l[50][50],m;
    printf("Enter the number of rows.");
    scanf("%d",&m);
    for(i=1;i<=m;i++)
    {
        for(j=0;j<(m-i);j++)
        printf("   ");
        for(j=0;j<i;j++)
        {
            k[0]=1;
            if(j==i-1)
            k[j]=1;
            l[i][j]=k[j];
            k[j+1]=l[i-1][j]+l[i-1][j+1];
            printf("%5d ",k[j]);
        }
        printf("\n");
    }
}

Related Links :

C Program to print multiple diamonds of $ | $ sign Diamond in C Language

C Program to print multiple diamonds of  $ | $ sign Diamond in C Language



#include
main()
{
    int j,i,k,l,m,n;
    char c;
    do
    {
        printf("Enter the number of dollars in the base..");
        scanf("%d",&k);
        printf("\nEnter the number of diamonds you want ..");
        scanf("%d",&n);
        printf("\n\n");
        for (i=1;i<=k;i++)
        {
            for(m=1;m<=n;m++)
            {
                for(l=0;l<(k-i);l++)
                printf(" ");
                for (j=0;j<i;j++)
                printf ("$ ");
                for(l=0;l<(k-i);l++)
                printf(" ");
            }
            printf("\n");
        }
        for (i=1;i<=k;i++)
         {
            for(m=1;m<=n;m++)
            {
                printf(" ");
                for(l=1;l<i;l++)
                printf(" ");
                for (j=1;j<=k-i;j++)
                printf ("$ ");
                for(l=0;l<i;l++)
                printf(" ");
            }
            printf("\n");
          }
        printf("\nEnter y to try more...press any other key exit...\t");
        c=getchar();
        c=getchar();
        putchar('\n');
    }
    while(c=='y');
}




Related Links :

C Program add two given numbers using user defined Function | UDF to add to number in C

C Program add two given numbers using user defined Function | UDF to add to number in C



#include
int getsum(int a,int b);       //declaration of function
int main()
{
    int i,j,k;
    printf("The program to add two numbers.\n");
    printf("Enter first number.\n");
    scanf("%d",&i);
    printf("Enter second number.\n");
    scanf("%d",&j);
    k=getsum(i,j);
    printf("Sum = %d\n",k);
}
int getsum(int a,int b)       //definition of function
{
  int temp;
  temp=a+b;
  return temp;
}



Related Links :

Finding whether a number is Armstrong number of not in C | C program to find given number Armstrong or not

Finding whether a number is Armstrong number of not in C | C program to find given number Armstrong or not | Armstrong number finding in C | C assignment to find given number is Armstrong or not 





/*Find whether entered number is armstrong number or not*/
#include
#include
int digit_count(int x);
int isArmstrong(int x);

int main()
{
    int flg=0,num;
    printf("This is a program to find whether a number is armstrong number\n");
    printf("enter a natural number\n");
    scanf("%d",&num);
    if(isArmstrong(num))
    printf("%d is an armstrong number\n",num);
    else
    printf("%d is not an armstrong number\n",num);
    getchar();
    return 0;
}

int digit_count(int x)
{
    int count=0;
    if(x==0)
    return 0;
    while(x/=10)
    count++;
    return count+1;
}

int isArmstrong(int x)
{
    int i,num_digit,sum=0,current_digit,holder;
    num_digit = digit_count(x);
    holder=x;
    for(i=0;i<num_digit;i++)
    {
        current_digit = x%10;
        sum+=pow(current_digit,num_digit);
        x/=10;
    }
    if(sum==holder)
    return 1;
    else
    return 0;
}

Related Links :

insertion sort in C | C program to show insertion sort | insertion example in C programming | C language insertion sort

insertion sort in C | C program to show insertion sort | insertion example in C programming | C language insertion sort | concept of insertion sort | working of insertion sort in C language | C Programming insertion Sorting






#include
void insert_sort(int a[],int size);
int main()
{
    int i,size;
    printf("program for sorting using insert sort\nHow many numbers do you want to sort\n");
    scanf("%d",&size);
    int arr[size];
    printf("enter numbers\n");
    for(i=0;i<size;i++)
    scanf("%d",&arr[i]);
    
    printf("the array before sort is\n");
    for(i=0;i<size;i++)
    printf("%d ",arr[i]);
    printf("\n");
    insert_sort(arr,size);
    printf("the array after sort is\n");
    for(i=0;i<size;i++)
    printf("%d ",arr[i]);
    printf("\n");
    return 0;
}

void insert_sort(int a[],int size)
{
    int i,j,k,temp;
    for(i=1;i<size;i++)
    {
        j=0;
        temp=a[i];
        while(temp>a[j]&&j<i)
        j++;
        for(k=i;k>j;k--)
            a[k]=a[k-1];
        a[k]=temp;
    }
}

Related Links :

C program to find nth term of Fibonacci series unlimited number | Unlimited Fibonacci series in C Language | upto nth number Fibonacci series in C language

C program to find nth term of Fibonacci series unlimited number | Unlimited Fibonacci series  in C Language | upto nth number Fibonacci series in C language




#define MAX 2100  
#include 
#include 
#include 
void print(char x[]); 
void add(char x[], char y[], char z[]); 

int main() 
{  
    int i=0,j,num; 
    char n_minus1[MAX]="1",n_minus2[MAX]="1",nth[MAX]=""; 
    printf("This is a program to print fibonacci sequence upto desired term.(max 10000)\n"); 
    printf("\nenter a natural number upto which do you want fibonacci series\n");
    scanf("%d",&num); 
    if(    num<1||num>10000) 
    { 
        printf("The desired term index was either invalid or greater than 10000\n"); 
        exit(0); 
    }
    printf("\noptions:\n1. print only %dth term\n2. print all terms\n",num);
    scanf("%d",&j);
    switch(j)
    {
        case 1: 
                if(num<2){
                printf("The first term is 1\n");
                break;
                }
                if(num<3){
                printf("The second term is 1\n");
                break;
                }
                for(i=2;i<num;i++)
                {
                  add(nth,n_minus1,n_minus2);
                  strcpy(n_minus2,n_minus1);
                  strcpy(n_minus1,nth);
                }
                printf("The %dth term is ",num);
                print(nth);
                break;
        case 2:    printf("\nFibonacci series upto %dth term\n\n",num);
                printf("term \tvalue\n",num);
                printf("%4d \t1\n",1);
                if(num<2)
                break;
                printf("%4d \t1\n",2);
                if(num<3)
                break;
                for(i=2;i<num;i++)
                {
                  add(nth,n_minus1,n_minus2);
                  printf("%4d\t",i+1);
                  print(nth);
                  strcpy(n_minus2,n_minus1);
                  strcpy(n_minus1,nth);
                }
                break;
        default: printf("Invalid choice...!!! \tExiting\n");
                exit(0);
    }
    printf("\n\nprgram finished successfully.\t press any key to continue\n");
    getchar(); 
    return 0; 
} 

void print(char x[]) 
{ 
    int i; 
    for(i=strlen(x)-1;i>=0;i--) 
    { 
        putchar(x[i]); 
        if(i%5==0) 
        putchar(' '); 
    } 
    putchar('\n'); 
    return; 
} 

void add(char x[],char y[],char z[]) 
{ 
    int i,ylen,zlen,equal;
    char c = 0,temp;
    ylen = strlen(y);
    zlen = strlen(z);
    equal = (ylen == zlen) ? 1 : 0; 
    for(i=0;i<zlen;i++) 
    { 
        x[i]=c + y[i] + z[i] - '0'; 
        if( x[i]-'0' > 9)
        {
            x[i]-=10;
            c=1;
        }
        else
        c=0; 
    }
    if(equal)
    {
        if(c!=0)
        {
            x[i]=c + '0';
            x[i+1]='\0';
        }
    }
    else
    {
        x[i]=c + y[i];
        x[i+1]='\0';
    } 
    return; 
}

Related Links :

C program to calculate antilog | C program to calculate antilog in c language

C program to calculate antilog | C program to calculate antilog in c language



#include 
#include 
main()
{
    printf("******program to calculate antilog in C language*******\n\n");
    double i,j;
    printf ("enter the value of P to get its antilog...\n\n\n P= ");
    scanf ("%lf",&i);
    printf("i=%lf\n",i);
    j=pow(10,i);
    printf("antilog P=%lf \n",j);
}


Related Links :

Reversing order of words in a sentence using stack in C Language | C Program to Reverse the sentence

Reversing order of words in a sentence using stack in C Language | C Program to Reverse the sentence



#include
#include
#include

struct linked_list
{
    char *chr;
    struct linked_list *next;
};
typedef struct linked_list node;
void push(node **p,char *x);
char *pop(node **p);

int main()
{
    char a[50],*temp,*dup;
    strcpy(a,"Hello Friends how are you... Enjoy lernc.blogspot.com ");
    node * head=NULL;
    temp=strtok(a," ");
    while(temp != NULL)
    {
        dup=strdup(temp);
        temp=strtok(NULL," ");
        push(&head,dup);
    }
    strcpy(a,"");
    while((temp=pop(&head))!=NULL)
    {
        strcat(a,temp);
        strcat(a," ");
    }
    a[strlen(a)-1]='\0';
    printf("%s\n",a);
    return 0;
}

void push(node **p,char *x)
{
    node *new_node;
    new_node=(node *)malloc(sizeof(node));
    new_node->chr=x;
    new_node->next=*p;
    *p=new_node;
}

char *pop(node **p)
{
    char *temp=NULL;
    node *tmp;
    if(*p==NULL)
        return (NULL);
    else
    {
        temp=(*p)->chr;
        tmp=*p;
        (*p)=(*p)->next;
        free(tmp);
        return (temp);
    }
}

Related Links :

Counting total number of nodes in a tree in C | C Program to count Nodes in tree

Counting total number of nodes in a tree in C | C Program to count Nodes in tree




#include
#include
struct tree_node
{
 int data;
 struct tree_node *left,*right,*parent;
};
typedef struct tree_node node;
node * new_node(int x);
node * insert_node(node *root, int x);
int count_nodes(node *root);

int main()
{
 node *root=NULL;
 int i,x,max;
 printf("how many numbers do you want to enter in tree?\n");
 scanf("%d",&max);
 printf("Enter %d numbers \n",max);
 for(i=0;idata > x)
  root->left = insert_node(root->left,x);
 else
  root->right = insert_node(root->right,x);
 return root;
}

int count_nodes(node *root)
{
 if(!root)
 return 0;
 else
 return(count_nodes(root->left) + 1 + count_nodes(root->right));
}

node * new_node(int x)
{
 node *furnished;
 furnished = (node*)malloc(sizeof(node));
 furnished->data=x;
 furnished->left=NULL;
 furnished->right=NULL;
 furnished->parent=NULL;
 return furnished;
}

Related Links :

c program that sort 10 numbers using shell sorting method | Shell Soring in C | Number sorting in C using Shell Sorting method | Shell Sorting method C Language

c program that sort 10 numbers using shell sorting method | Shell Soring in C | Number sorting in C using Shell Sorting method | Shell Sorting method C Language






#include
#include
int main()
{
 int arr[30];
 int i,j,k,tmp,num;
 printf("Enter total no. of elements : ");
 scanf("%d", &num);
 for(k=0; k<num; k++)
 {
   printf("\nEnter %d number : ",k+1);
   scanf("%d",&arr[k]);
 }
 for(i=num/2; i>0; i=i/2)
 {
   for(j=i; j<num; j++)
   {
     for(k=j-i; k>=0; k=k-i)
     {
        if(arr[k+i]>=arr[k])
            break;
        else
        {
            tmp=arr[k];
            arr[k]=arr[k+i];
            arr[k+i]=tmp;
        }
     }
   }
 }
 printf("\t**** Shell Sorting ****\n");
 for(k=0; k<num; k++)
     printf("%d\t",arr[k]);
 getch();
 return 0;
}

Related Links :

C program to find nCr using function | C Assignment to Find nCr in C Language

C program to find nCr using function | C Assignment to Find nCr in C Language





#include
 
long factorial(int);
long find_ncr(int, int);
long find_npr(int, int);
 
main()
{
   int n, r;
   long ncr, npr;
 
   printf("Enter the value of n and r\n");
   scanf("%d%d",&n,&r);
 
   ncr = find_ncr(n, r);
   npr = find_npr(n, r);
 
   printf("%dC%d = %ld\n", n, r, ncr);
   printf("%dP%d = %ld\n", n, r, npr);
 
   return 0;
}
 
long find_ncr(int n, int r)
{
   long result;
 
   result = factorial(n)/(factorial(r)*factorial(n-r));
 
   return result;
}
 
long find_npr(int n, int r)
{
   long result;
 
   result = factorial(n)/factorial(n-r);
 
   return result;
} 
 
long factorial(int n)
{
   int c;
   long result = 1;
 
   for( c = 1 ; c <= n ; c++ )
      result = result*c;
 
   return ( result );
}

Related Links :

C Program to Sort Given Numbers, c program for merge sorting, Merge Sorting of Numbers in C, assignment to merge sorting in c

C Program to Sort Given Numbers, c program for merge sorting, Merge Sorting of Numbers in C, assignment to merge sorting in c





#include
#include
void merge(int [],int ,int ,int );
void part(int [],int ,int );
int main()
{
 int arr[30];
 int i,size;
 printf("\n\t------- Merge sorting method -------\n\n");
 printf("Enter total no. of elements : ");
 scanf("%d",&size);
 for(i=0; i<=size; i++)
 {
   printf("Enter %d element : ",i+1);
   scanf("%d",&arr[i]);
 }
 part(arr,0,size-1);
 printf("\n\t------- Merge sorted elements -------\n\n");
 for(i=0; i<=size; i++)
 printf("%d ",arr[i]);
 getch();
 return 0;
}


void part(int arr[],int min,int max)
{
 int mid;
 if(min<max)
 {
   mid=(min+max)/2;
   part(arr,min,mid);
   part(arr,mid+1,max);
   merge(arr,min,mid,max);
 }
}


void merge(int arr[],int min,int mid,int max)
{
  int tmp[30];
  int i,j,k,m; 
  j=min;
  m=mid+1;
  for(i=min; j<=mid && m<=max ; i++)
  {
     if(arr[j]<=arr[m])
     {
         tmp[i]=arr[j];
         j++;
     }
     else
     {
         tmp[i]=arr[m];
         m++;
     }
  }
  if(j>mid)
  {
     for(k=m; k<=max; k++)
     {
         tmp[i]=arr[k];
         i++;
     }
  }
  else
  {
     for(k=j; k<=mid; k++)
     {
        tmp[i]=arr[k];
        i++;
     }
  }
  for(k=min; k<=max; k++)
     arr[k]=tmp[k];
}

Related Links :

C Program to print Number rhombus , Creating rhombus shape in C, rhombus Shape in C

C Program to print Number rhombus , Creating rhombus shape in C, rhombus Shape in C





#include
#include
int main()
{
 int num,r,c,sp;
 printf("Enter number of rows : ");
 scanf("%d",&num);
 for(r=1; r<=num; r++)
 {
   for(sp=num-r; sp>0; sp--)
       printf(" ");
   for(c=r; c>=1; c--)
       printf("%d",c);
   for(c=2; c<=r; c++)
       printf("%d",c);
   printf("\n");
 }
 for(r=1; r<=num; r++)
 {
   for(sp=r; sp>=1; sp--)
       printf(" ");
   for(c=num-r; c>=1; c--)
       printf("%d",c);
   for(c=2; c<=num-r; c++)
       printf("%d",c);
   printf("\n");
 }
 getch();
 return 0;
}

Related Links :

c program to print diamond pattern, C Program to Print Diamond in C , Diamond Shape in C Language, C Assignment to print Diamond shape in C

c program to print diamond pattern, C Program to Print Diamond in C , Diamond Shape in C Language, C Assignment to print Diamond shape in C





#include 
 
int main()
{
  int n, c, k, space = 1;
 
  printf("Enter number of rows\n");
  scanf("%d", &n);
 
  space = n - 1;
 
  for (k = 1; k <= n; k++)
  {
    for (c = 1; c <= space; c++)
      printf(" ");
 
    space--;
 
    for (c = 1; c <= 2*k-1; c++)
      printf("*");
 
    printf("\n");
  }
 
  space = 1;
 
  for (k = 1; k <= n - 1; k++)
  {
    for (c = 1; c <= space; c++)
      printf(" ");
 
    space++;
 
    for (c = 1 ; c <= 2*(n-k)-1; c++)
      printf("*");
 
    printf("\n");
  }
 
  return 0;
}


OUTPUT : 


  *
 ***
*****
 ***
  *

Related Links :

C Program to Print Inverse Pyramid of ABCD... in C | Pyramid of Alphabets in C | Reverse Pyramid in C | Reverse Triangle In C

C Program to Print Inverse Pyramid of ABCD... in C | Pyramid of Alphabets in C | Reverse Pyramid in C | Reverse Triangle In C | Reverse Pyramid of ABC in C Language, Printing ABCD Pyramid in C language





#include
 
main()
{
      char ch = 'A';
      int n, c, k, space = 0;
 
      scanf("%d", &n);
 
      for ( k = n ; k >= 1 ; k-- )
      {
          for ( c = 1 ; c <= space ; c++)
              printf(" ");
 
          space++;
 
          for ( c = 1 ; c <= k ; c++ )
          {
             printf("%c ", ch); 
             ch++;
          }
 
          printf("\n");
          ch = 'A';
      }
 
      return 0;
}




Output : 
A B C D E F G H
 A B C D E F G
  A B C D E F 
   A B C D E
    A B C D 
     A B C
      A B
       A




Related Links :

C Program to print inverse triangle of Numbers in c, inverted triangle in C, invert right triangle in C

C Program to print inverse triangle of Numbers in c, inverted triangle in C, invert right triangle in C


1 2 3 4 5 

  1 2 3 4 

     1 2 3

        1 2 

           1





#include
 
main()
{
   int n, c, k, space;
 
   scanf("%d", &n);
 
   space = 0;
 
   for ( k = n ; k >= 1 ; k-- )
   {
       for ( c = 1 ; c <= space ; c++ )
       printf(" ");
 
       space++;
 
       for ( c = 1 ; c <= k ; c++)
          printf("%d", c);
 
       printf("\n");
   }
 
   return 0;
}



OUTPUT : 

12345
 1234
  123
   12
    1

Related Links :

c program to print patterns of numbers and stars | Printing Patterns of Stars and numbers in C | Star pyramids , triangles in C | C assignments to print pyramid of stars

c program to print patterns of numbers and stars | Printing Patterns of Stars and numbers in C | Star pyramids , triangles in C | C assignments to print pyramid of stars





#include
 
main()
{
   int row, c, n, temp;
 
   printf("Enter the number of rows in pyramid of stars you want to create");
   scanf("%d",&n);
 
   temp = n;
 
   for ( row = 1 ; row <= n ; row++ )
   {
      for ( c = 1 ; c < temp ; c++ )
         printf(" "); // to print space 
 
      temp--;
 
      for ( c = 1 ; c <= 2*row - 1 ; c++ )
         printf("*"); // to print star symbol in pyramid 
 
      printf("\n");
   }
 
   return 0;
}


Related Links :

Logic of HCF or GCD of any two numbers in C Language | Understand Logic of HCF and GCD in C

Logic of HCF or GCD of any two numbers in C Language | Understand Logic of HCF and GCD in C



In HCF we try to find any largest number which can
divide both the number.
For example:

HCF or GCD of 20 and 30
Both number 20 and 30 are divisible by 1, 2,5,10.
HCF=max (1, 2, 3, 4, 10) =10

Logic for writing program:

It is clear that any number is not divisible by greater than number itself. In case of more than one numbers, a possible maximum number which can divide all of the numbers must be minimum of all of that numbers.

For example: 10, 20, and 30
Min (10, 20, 30) =10 can divide all there numbers. So we will take one for loop which will start form min of the numbers and will stop the loop when it became one, since all numbers are divisible by one. Inside for loop we will write one if conditions which will check divisibility of both the numbers.

Related Links :

HCF program with multiple numbers in c | Program to Find Multiple Number Input, Find HCF in C | Find HCF From Given Numbers in C

HCF  program with multiple numbers in c | Program to Find Multiple Number Input, Find HCF in C | Find HCF From Given Numbers in C





#include 
int main()
{
int x,y=-l;
printf("Insert numbers. To exit insert zero: ");
while(1)
{
scanf("%d",&x); 
if(x<1)
break; 
else 
if(y==-1)
y=x; 
else 
if (x=l;i--)
{
if(x%i==0 && y%i==0)
{
break;
}
}
return i;
}

Related Links :

C Program to find HCF (Highest common factor) using while loop | Program to Find HCF in C Language

C Program to find HCF (Highest common factor) using while loop | Program to Find HCF in C Language





HCF (Highest common factor)  program with two numbers in c


#include 
int main () 
{
int nl,n2;
printf("\nEnter two numbers:"); 
scanf("%d %d",&nl,&n2); 
while(nl!=n2)
{
if(nl>=n2-l)
nl=nl-n2; else
n2=n2-nl;
}
printf("\nGCD=%d",nl); 
return 0; 
}

Related Links :

C Program to Print Pattern of Numbers in C | Number Pattern in C Language

C Program to Print Pattern of Numbers in C | Number Pattern in C Language





#include 
#include 
void main()
{
int i=0,j=0,no=0;
clrscr();
printf("\n Please Enter The Numbers...);
scanf("%d",&no);
for(i=l;i<=no;i++)
{
printf(\n"); 
for(j=l;j<=i;j++)
{
printf("%d",j);
}
for(j=no;j>0;j--)
{
if(j<=i)
printf("%d",j);
}
}
getch();
}

Related Links :

C Program to Print patterns of Stars | Star Patterns Printing in C

C Program to Print patterns of Stars | Star Patterns Printing in C





#include 
#include 
void main()
{
int i=0,no=0,j=0;
clrscr();
printf("\n Please Enter The Number);
scanf("%d",&no);
for(i=0;i<=no;i++)
{
printf C\n") ; 
for(j=0;j<=no;j++)
}
if(i==j)
printf("*");
else
printf(" ");
}
}
getch();
}

Related Links :

THE # DEFINE DIRECTIVE in C Language

THE # DEFINE DIRECTIVE in C Language | Working of #Define



The #define directive is used to define a symbol to the preprocessor and assign it a value. The symbol is meaningful to the preprocessor only in the lines of code following the definition. For example, if the directive #define NULL 0 is included in the program, then in all lines following the definition, the symbol NULL is replaced by the symbol. If the symbol NULL is written in the program before the definition is encountered, however, it is not replaced.
The # define directive is followed by one or more spaces or tabs and the symbol to be defined. The syntax of a preprocessor symbol is the same as that for a C variable or function name. It cannot be a C keyword or a variable name used in the program; if it is so a syntax error is detected by the compiler.

Related Links :

C Program to create generic macro to swap two values

C Program to create generic macro to swap two values



The best all-around solution is probably to forget about using a macro, unless you're willing to pass in the type as a third argument. (Also, if you're trying to swap entire structures or arrays, you probably want to exchange pointers instead.) If you're worried about the use of an ugly temporary, and know that your machine provides an efficient exchange instruction, convince your compiler vendor to recognize the standard three-assignment swap idiom in the optimization phase.

Related Links :

c program to find the volume and surface area of cuboids | volume and surface area of cuboids Calculate in C Language | C Program to find volume and surface area of cuboids

c program to find the volume and surface area of cuboids | volume and surface area of cuboids Calculate in C Language | C Program to find volume and surface area of cuboids

 



#include

int main(){

    float w,l,h;
    float surface_area,volume,space_diagonal;

    printf("Enter size of width, length and height of a cuboids : ");
    scanf("%f%f%f",&w,&l,&h);

    surface_area = 2*(w*l + l*h + h*w);
    volume = w * l * h;
    space_diagonal = sqrt(w*w + l*l + h*h);

    printf("Surface area of cuboids is: %.3f",surface_area);
    printf("\nVolume of cuboids is : %.3f",volume);
    printf("\nSpace diagonal of cuboids is : %.3f",space_diagonal);

    return 0;
}

Related Links :

C program for area of a trapezium | Find Area of Trapezium in C Language | Area of Trapezium in C Language

C program for area of a trapezium | Find Area of Trapezium in C Language | Area of Trapezium in C Language





#include

int main(){

    float b1,b2,h;
    float area;

    printf("Enter the size of two bases and height of the trapezium : ");
    scanf("%f%f%f",&b1,&b2,&h);

    area = 0.5 * ( b1 + b2 ) * h ;

    printf("Area of trapezium is: %.3f",area);

    return 0;
}

Related Links :

c program to find the area of a right angled triangle

c program to find the area of a right angled triangle | Program to Find Area of Right Angled Triangle in C language





#include

int main(){

    float h,w;
    float area;

    printf("Enter height and width of the right angled triangle : ");
    scanf("%f%f",&h,&w);

    area = 0.5 * h * w;

    printf("Area of right angled triangle is: %.3f",area);

    return 0;
}

Related Links :

C program for area of equilateral triangle | Area of equilateral Triangle in C language

C program for area of equilateral triangle | Area of equilateral Triangle in C language





#include
#include

int main(){

    float a;
    float area;

    printf("Enter size of side of the equilateral triangle : ");
    scanf("%f",&a);

    area = sqrt(3)/4*(a*a);

    printf("Area of equilateral triangle is: %.3f",area);

    return 0;
}

Related Links :

c program to find the volume and surface area of sphere | Program to find area of sphere in C language | C Language Volume of Sphere

c program to find the volume and surface area of sphere | Program to find area of sphere in C language | C Language Volume of Sphere






#include
#include

int main(){

    float r;
    float surface_area,volume;

    printf("Enter radius of the sphere : ");
    scanf("%f",&r);

    surface_area =  4* M_PI * r * r;
    volume = (4.0/3) * M_PI * r * r * r;

    printf("Surface area of sphere is: %.3f",surface_area);
    printf("\nVolume of sphere is : %.3f",volume);

    return 0;
}


Related Links :

C Language convert string to int | Converting String to Integer in C

C Language  convert string to int | Converting String to Integer in C  

 



Method 1:

#include
#include
int main(){
    char str[50];
    int number;

    //Accepting a numer in string format
    printf("Enter any number as a string : ");
    scanf("%s",str);
   
    //Converting string into the number;
    number = atoi(str);
         if(number==0 && str[0]!='0')
             printf("\nInvalid number");
         else
             printf("\n Equivalent number is : %d",number);
    return 0;
}

Method 2:

#include
#include
#include
#include

char * toString(int);
int main(){
    int number;
    char *string;

    //Accepting a number from user
    printf("Enter any integer number : ");
    scanf("%d",&number);

    //Checking number is valid or not
    if(isdigit(number)==0){
         printf("\nInvalid number");
         //exit(1);  //to exit from program
    }

    //Converting int to string
    string = toString(number);

    //printing the string in console
    printf("\nEqivalent string: %s",string);
    return 0;   
}

//function to conver int into string
char * toString(int num){
    static char str[50];
    char *ptr =(char *) #
    int i,length=0,temp,le;
    temp=num;
    while(temp){
         temp = temp/10;
         length++;
    }
    le=length;
    printf("le %d",length);
    for(i=0;i<=le;i++){
         printf("%d",num/pow(10,length) + 48);
         num= num + (pow(10,length--));
    }
    str[i]='\0';
    return str;
}

Related Links :

Different ways to initialize the array in C | initialize the array in C | Ways to initialize the array in C Language

Different ways to initialize the array in C | initialize the array in C | Ways to initialize the array in C Language





We can initialize the array either at the time of declaration of after the declaration
For example: Initialization of an array at time of declaration:
int arr1[5] ={1,2,3,4,5};
Note: Size of an array is optional when we are initializing it at the time of declaration.
For example:
int arr2[]={1,2,3,4};
In this case size of array is number of elements i.e. 4
Initialization of an array after the declaration
int arr3[5]; //declaration of array
Initialization of array
arr[0]=1;
arr[1]=2;
arr[2]=3;
arr[3]=4;
arr[4]=5;
Initialization of multidimensional array at the time of declaration
int arr4[3][2]= {{1,2},{3,4},{5,6}};
Note: size of first dimension is optional when we are initializing it at the time of declaration.
For example:
int arr5[][3]={{1,2,3},{1},{2,3}};
Size of first dimension will adjust according to number of elements. In this case it is three.
Default value of rest element is zero in case of integer array.
We can also initialize multidimensional array at the time of declaration with using inner {}.
For example:
int arr6[][2][3]={1,2,3,4};
In this case default value of rest elements are zero.
Declaration of multidimensional array:
int arr[3][2]; //Declaration of array
Initialization of multidimensional array
arr[0][0]=1;
arr[0][1]=2;
arr[1][0]=3;
arr[1][1]=4;
arr[2][0]=5;


Related Links :

Program to generate Random numbers in c | Random Numbers in C | Random Numbers printing in C

Program to generate Random numbers in c | Random Numbers in C | Random Numbers printing in C




#include
#include
#include
int main(){
    int num;

    //initialize the random number generator
    randomize();

    //Generating the random number
    num = random(99999);

    //Printing the random number
    printf("%d",num);
    getch();
    return 0;
}

Related Links :

Adding Node to List in Data Structure | DS Adding Link


Related Links :

C program for searching a Node in List | Link List Searching in C

C program for searching a Node in List | Link List Searching in C



Data values are given which we call a key and a binary search tree. To search for the key in the given binary search tree, start with the root node and compare the key with the data value of the root node. If they match, return the root pointer. If the key is less than the data value of the root node, repeat the process by using the left subtree. Otherwise, repeat the same process with the right subtree until either a match is found or the subtree under consideration becomes an empty tree.




#include 
#include 
struct tnode
{
  int data;
  struct tnode *lchild, *rchild;
};
/* A function to serch for a given data value in a binary search tree*/
struct tnode *search( struct tnode *p,int key)
   {
     struct tnode *temp;
      temp = p;
     while( temp != NULL)
       {
         if(temp->data == key)
                return(temp);
         else
   if(temp->data > key)
      temp = temp->lchild;
   else
      temp = temp->rchild;
        }
return(NULL);
}

/*an iterative function to print the binary tree in inorder*/
void inorder1(struct tnode *p)
{
  struct tnode *stack[100];
  int top;
  top = −1;
 if(p != NULL)
 {
    top++;
    stack[top] = p;
    p = p->lchild;
    while(top >= 0)
       {
          while ( p!= NULL)/* push the left child onto stack*/
           {
                       top++;
                 stack[top] =p;
                 p = p->lchild;
         }
         p = stack[top];
         top-;
         printf("%d\t",p->data);
         p = p->rchild;


         if ( p != NULL) /* push right child*/
           {
               top++;
                              stack[top] = p;
               p = p->lchild;
                 }

         }
    }
}
/* A function to insert a new node in binary search tree to
get a tree created*/
struct tnode *insert(struct tnode *p,int val)
{
   struct tnode *temp1,*temp2;
   if(p == NULL)
   {
      p = (struct tnode *) malloc(sizeof(struct tnode)); /* insert the new node as root node*/
      if(p == NULL)
        {
   printf("Cannot allocate\n");
   exit(0);
       }
    p->data = val;
    p->lchild=p->rchild=NULL;
   }
  else
  {
    temp1 = p;
   /* traverse the tree to get a pointer to that node whose child will be the newly created node*/
  while(temp1 != NULL)
  {
    temp2 = temp1;
    if( temp1 ->data > val)
         temp1 = temp1->lchild;
    else
         temp1 = temp1->rchild;
  }
  if( temp2->data > val)
  {
      temp2->lchild = (struct tnode*)malloc(sizeof(struct tnode));/ *inserts the newly created node
  as left child*/
     temp2 = temp2->lchild;
     if(temp2 == NULL)
          {
     printf("Cannot allocate\n");
     exit(0);
          }
    temp2->data = val;
    temp2->lchild=temp2->rchild = NULL;
  }
  else
  {
     temp2->rchild = (struct tnode*)malloc(sizeof(struct tnode));/ *inserts the newly created node
  as left child*/
     temp2 = temp2->rchild;
     if(temp2 == NULL)
          {
     printf("Cannot allocate\n");
     exit(0);
         }
     temp2->data = val;
     temp2->lchild=temp2->rchild = NULL;
  }
}
return(p);
}
void main()
{
   struct tnode *root = NULL, *temp = NULL;
   int n,x;
   printf("Enter the number of nodes in the tree\n");
   scanf("%d",&n);
   while( n - > 0)
       {
         printf("Enter the data value\n");
         scanf("%d",&x);
         root = insert(root,x);
       }
      printf("The created tree is :\n");
      inorder1(root);
      printf("\n Enter the value of the node to be searched\n");
      scanf("%d",&n);
      temp=search(root,n);
      if(temp != NULL)
          printf("The data value is present in the tree \n");
      else
          printf("The data value is not present in the tree \n");
}


Explanation

  • Input: 1. The number of nodes that the tree to be created should have
    2. The data values of each node in the tree to be created
    3. The key value
  • Output: If the key is present and appears in the created tree, then a message
    "The data value is present in the tree" appears. Otherwise the message
    "The data value is not present in the tree" appears.

Related Links :

C program to delete a node, where the data value of the node to be deleted is known | DS Deleting Node Link List | Link List Program for node deletion

C program to delete a node, where the data value of the node to be deleted is known | DS Deleting Node Link List | Link List Program for node deletion




#include 
#include 
struct tnode
{
  int data;
  struct tnode *lchild, *rchild;
};
/* A function to get a pointer to the node whose data value is given
    as well as the pointer to its root */
struct tnode *getptr(struct tnode *p, int key, struct tnode **y)
{
  struct tnode *temp;
     if( p == NULL)
       return(NULL);
     temp = p;
     *y = NULL;
      while( temp != NULL)
       {
         if(temp->data == key)
             return(temp);
         else
     {
             *y = temp; /*store this pointer as root */
     if(temp->data > key)
        temp = temp->lchild;
     else
        temp = temp->rchild;
        }
       }
      return(NULL);
}

/* A function to delete the node whose data value is given */
struct tnode *delete(struct tnode *p,int val)
  {
    struct tnode *x, *y, *temp;
    x = getptr(p,val,&y);
    if( x == NULL)
    {
      printf("The node does not exists\n");
      return(p);
    }
    else
    {
    /* this code is for deleting root node*/
    if( x == p)
      {
        temp = x->lchild;
        y = x->rchild;
        p = temp;
        while(temp->rchild != NULL)
      temp = temp->rchild;
      temp->rchild=y;
      free(x);
      return(p);
    }
/* this code is for deleting node having both children */
  if( x->lchild != NULL && x->rchild != NULL)
     {

       if(y->lchild == x)
       {
temp = x->lchild;
y->lchild = x->lchild;
while(temp->rchild != NULL)
    temp = temp->rchild;
temp->rchild=x->rchild;
x->lchild=NULL;
x->rchild=NULL;
        }
        else
        {
          temp = x->rchild;
          y->rchild = x->rchild;
           while(temp->lchild != NULL)
      temp = temp->lchild;
    temp->lchild=x->lchild;
x->lchild=NULL;
 x->rchild=NULL;
         }

free(x);
   return(p);
  }
   /* this code is for deleting a node with on child*/
   if(x->lchild == NULL && x->rchild !== NULL)
     {
       if(y->lchild == x)
  y->lchild = x->rchild;
          else
            y->rchild = x->rchild;
          x->rchild; = NULL;
          free(x);
          return(p);
       }
       if( x->lchild != NULL && x->rchild == NULL)
         {
           if(y->lchild == x)
              y->lchild = x->lchild ;
           else
              y->rchild = x->lchild;
           x->lchild = NULL;
           free(x);
           return(p);
         }
       /* this code is for deleting a node with no child*/
       if(x->lchild == NULL && x->rchild == NULL)
        {
           if(y->lchild == x)
              y->lchild = NULL ;
           else
              y->rchild = NULL;
           free(x);
           return(p);
        }
    }
}
/*an iterative function to print the binary tree in inorder*/
void inorder1(struct tnode *p)
{
 struct tnode *stack[100];
 int top;
 top = −1;
if(p != NULL)
 {
    top++;
    stack[top] = p;
    p = p->lchild;
    while(top >= 0)
       {
          while ( p!= NULL)/* push the left child onto stack*/
           {
                       top++;
                 stack[top] =p;
                 p = p->lchild;
 }
      p = stack[top];
      top-;
      printf("%d\t",p->data);
      p = p->rchild;
      if ( p != NULL) /* push right child*/
         {
             top++;
         stack[top] = p;
             p = p->lchild;
      }
   }
     }
   }
   /* A function to insert a new node in binary search tree to get a tree created*/
  struct tnode *insert(struct tnode *p,int val)
  {
     struct tnode *temp1,*temp2;
     if(p == NULL)
     {
        p = (struct tnode *) malloc(sizeof(struct tnode)); /* insert the new node as root node*/
        if(p == NULL)
          {
     printf("Cannot allocate\n");
     exit(0);
          }
       p->data = val;
       p->lchild=p->rchild=NULL;
  }
  else
  {
    temp1 = p;
   /* traverse the tree to get a pointer to that node whose child will be the newly created node*/
  while(temp1 != NULL)
  {
    temp2 = temp1;
    if( temp1 ->data > val)
         temp1 = temp1->lchild;
    else
         temp1 = temp1->rchild;
  }
  if( temp2->data > val)
  {
     temp2->lchild = (struct tnode*)malloc(sizeof(struct tnode));/ *inserts the newly created node
  as left child*/
     temp2 = temp2->lchild;
     if(temp2 == NULL)
          {
     printf("Cannot allocate\n");
     exit(0);
         }
    temp2->data = val;
    temp2->lchild=temp2->rchild = NULL;
  }
  else
  {
      temp2->rchild = (struct tnode*)malloc(sizeof(struct tnode));/ *inserts the newly created node
  as left child*/
     temp2 = temp2->rchild;
     if(temp2 == NULL)
          {
     printf("Cannot allocate\n");
     exit(0);
         }
    temp2->data = val;
    temp2->lchild=temp2->rchild = NULL;
  }
  }
  return(p);
  }

  void main()
  {
    struct tnode *root = NULL;
    int n,x;
    printf("Enter the number of nodes in the tree\n");
    scanf("%d",&n);
    while( n - > 0)
        {
          printf("Enter the data value\n");
          scanf("%d",&x);
          root = insert(root,x);
        }
       printf("The created tree is :\n");
       inorder1(root);
       printf("\n Enter the value of the node to be deleted\n");
       scanf("%d",&n);
       root=delete(root,n);
       printf("The tree after deletion is \n");
       inorder1(root);
} 
 

Explanation

This program first creates a binary tree with a specified number of nodes with their respective data values. It then takes the data value of the node to be deleted, obtains a pointer to the node containing that data value, and obtains another pointer to the root of the node to be deleted. Depending on whether the node to be deleted is a root node, a node with two children a node with only one child, or a node with no children, it carries out the manipulations as discussed in the section on deleting a node. After deleting the specified node, it returns the pointer to the root of the tree.
  • Input: 1. The number of nodes that the tree to be created should have
    2. The data values of each node in the tree to be created
    3. The data value in the node to be deleted
  • Output: 1. The data values of the nodes in the tree in inorder before deletion
    2. The data values of the nodes in the tree in inorder after deletion

Related Links :

program for building and printing the elements of the linked list

program for building and printing the elements of the linked list





# include 
   # include 
   struct node
   {
   int data;
   struct node *link;
   };
   struct node *insert(struct node *p, int n)
   {
   struct node *temp;
   /* if the existing list is empty then insert a new node as the
starting node */
   if(p==NULL)
   {
      p=(struct node *)malloc(sizeof(struct node)); /* creates new node
data value passes
   as parameter */

         if(p==NULL)
         {
      printf("Error\n");
             exit(0);
         }
         p-> data = n;
         p-> link = p; /* makes the pointer pointing to itself because it
is a circular list*/
      }
      else
      {
      temp = p;
   /* traverses the existing list to get the pointer to the last node of
   it */
      while (temp-> link != p)
         temp = temp-> link;
            temp-> link = (struct node *)malloc(sizeof(struct node)); /*
   creates new node using
             data value passes as
               parameter and puts its
             address in the link field
             of last node of the
             existing list*/
           if(temp -> link == NULL)
           {
         printf("Error\n");
              exit(0);
           }
           temp = temp-> link;
           temp-> data = n;
           temp-> link = p;
          }
          return (p);
   }
   void printlist ( struct node *p )
   {
   struct node *temp;
    temp = p;
   printf("The data values in the list are\n");
      if(p!= NULL)
      {
      do
            {
            printf("%d\t",temp->data);
            temp=temp->link;
            } while (temp!= p);
      }
      else
         printf("The list is empty\n");
   }

   void main()
   {
      int n;
      int x;
      struct node *start = NULL ;
      printf("Enter the nodes to be created \n");
      scanf("%d",&n);
      while ( n -- > 0 )
      {
   printf( "Enter the data values to be placed in a node\n");
         scanf("%d",&x);
         start = insert ( start, x );
      }
      printf("The created list is\n");
      printlist ( start );
   }


Explanation This program uses a strategy of inserting a node in an existing list to get the list created. An insert function is used for this. The insert function takes a pointer to an existing list as the first parameter, and a data value with which the new node is to be created as a second parameter, creates a new node by using the data value, appends it to the end of the list, and returns a pointer to the first node of the list. Initially the list is empty, so the pointer to the starting node is NULL. Therefore, when insert is called first time, the new node created by the insert becomes the start node. Subsequently, the insert traverses the list to get the pointer to the last node of the existing list, and puts the address of the newly created node in the link field of the last node, thereby appending the new node to the existing list. The main function reads the value of the number of nodes in the list. Calls iterate that many times by going in a while loop to create the links with the specified number of nodes. Points to Remember Linked lists are used when the quantity of data is not known prior to execution. In linked lists, data is stored in the form of nodes and at runtime, memory is allocated for creating nodes. Due to overhead in memory allocation and deallocation, the speed of the program is lower. The data is accessed using the starting pointer of the list.

Related Links :

Dangling pointer in C | Working with Dangling pointer | Dangling pointer Concept in C | Dangling pointer Examples in C | C Programming Dangling pointer

Dangling pointer in C | Working with Dangling pointer | Dangling pointer Concept in C | Dangling pointer Examples in C | C Programming Dangling pointer



If any pointer is pointing the memory address of any variable but after some variable has deleted from that memory location while pointer is still pointing such memory location. Such pointer is known as dangling pointer and this problem is known as dangling pointer problem.


#include

int *call();
void main(){

int *ptr;
ptr=call();

fflush(stdin);
printf("%d",*ptr);

}
int * call(){

int x=25;
++x;

return &x;
}


Output: Garbage value

variable x is local variable. Its scope and lifetime is within the function call hence after returning address of x variable x became dead and pointer is still pointing ptr is still pointing to that location. Solution of this problem: Make the variable x is as static variable.

Related Links :

Huge pointer in C | C language Huge Pointer | Huge Pointers in C Language | Huge Pointers Working in C | Concept of Huge Pointer

Huge pointer in C | C language Huge Pointer | Huge Pointers in C Language  | Huge Pointers Working in C | Concept of Huge Pointer


Well the Size of huge pointer is 4 byte or 32 bit.
The pointer which can point or access whole the residence memory of RAM i.e. which can access all the 16 segments is known as huge pointer.

Related Links :


If you face any Problem in viewing code such as Incomplete "For Loops" or "Incorrect greater than or smaller" than equal to signs then please collect from My Web Site CLICK HERE


More Useful Topics...

 

History Of C..

In the beginning was Charles Babbage and his Analytical Engine, a machine
he built in 1822 that could be programmed to carry out different computations.
Move forward more than 100 years, where the U.S. government in
1942 used concepts from Babbage’s engine to create the ENIAC, the first
modern computer.
Meanwhile, over at the AT&T Bell Labs, in 1972 Dennis Ritchie was working
with two languages: B (for Bell) and BCPL (Basic Combined Programming
Language). Inspired by Pascal, Mr. Ritchie developed the C programming
language.

My 1st Program...


#include
#include
void main ()
{
clrscr ();
printf ("\n\n\n\n");
printf ("\t\t\t*******Pankaj *******\n");
printf ("\t\t\t********************************\n");
printf ("\t\t\t\"Life is Good...\"\n");
printf ("\t\t\t********************************");
getch ();
}

Next Step...


#include
#include

void main ()
{
clrscr ();
printf ("\n\n\n\n\n\n\n\n");
printf ("\t\t\t --------------------------- \n\n");

printf ("\t\t\t | IGCT, Info Computers, INDIA | \n\n");
printf ("\t\t\t --------------------------- ");

getch ();

}

Hits!!!