Quantcast
Channel: C Programming Archives - QnA Plus
Viewing all 93 articles
Browse latest View live

C Programming – Basic

$
0
0

C Programming - Basic

Test your basic C programming skill.


General Knowledge – Set 1

$
0
0

General Knowledge - Set 1

Test your general knowledge skill set 1

C Programming – Data Types

$
0
0

C Programming - Data Types

Test your C Data Type skill. Answers can be viewed after completion of all questions.

C Program to Check Whether a Number is Palindrome

$
0
0

Palindrome is a number or sequence of characters which reads same backward and forward. If we reverse a palindrome number, the reversed and original number will be same. The first C program checks whether a number is palindrome by reversing the number. The second program does the same thing without reversing the number.

By reversing the number:

#include <stdio.h>

int reverse(int n)
{
    int r = 0;
    while(n)
    {
        r = r * 10 + n % 10;
        n = n / 10;
    }

    return r;
}

void main()
{
    int num = 0;

    printf("Enter an integer: ");
    scanf("%d", &num);


    if(num == reverse(num))
        printf("%d is palindrome\n", num);
    else
        printf("%d is not palindrome.\n", num);
}

Without reversing the number

#include <stdio.h>
#include <math.h>

int getdigit(int num, int n)
{
    int r, t1, t2;

    t1 = pow(10, n+1);
    r = num % t1;

    if (n > 0)
    {
        t2 = pow(10, n);
        r = r / t2;
    }

    return r;
}

int number_len(int n)
{
    int len = 0;

    while(n)
    {
        len++;
        n /= 10;
    }

    return len;
}
void main()
{
    int num = 0, i, len, flag = 1;

    printf("Enter an integer: ");
    scanf("%d", &num);

    len =  number_len(num);

    for (i = 0; i < len/2; i++)
    {
        if(getdigit(num, i) != getdigit(num, len - i - 1))
        {
            flag = 0;
            break;
        }
    }

    if(flag)
        printf("%d is palindrome.\n", num);
    else
        printf("%d is not palindrome.\n", num);
}

Outout:

Enter an integer: 4232
4232 is not palindrome.

Enter an integer: 65756
65756 is palindrome.

The post C Program to Check Whether a Number is Palindrome appeared first on QnA Plus.

C Program to Convert Decimal to Binary

$
0
0

Following C programs converts a decimal number to its binary equivalent.

Using recursive function

#include <stdio.h>

void binary(int n)
{
    if(n > 0)
    {
        binary(n/2);
        printf("%d", n%2);
    }
}

void main()
{
    int num = 0;

    printf("Enter an integer: ");
    scanf("%d", &num);

    printf("Binary of %d: ", num);
    binary(num);
    printf("\n");
}

Without recursive function

#include <stdio.h>

void main()
{
    int num = 0, i, tmp;

    printf("Enter an integer: ");
    scanf("%d", &num);

    printf("Binary of %d: ", num);

    i = sizeof(num) * 8 - 1;

    while(i >= 0) printf("%d", (num >> i--)&1?1:0);

    printf("\n");
}

Output:

Enter an integer: 534
Binary of 534: 1000010110

The post C Program to Convert Decimal to Binary appeared first on QnA Plus.

C Program to Get a Digit of Any Position of a Number

$
0
0

This C program finds the digit of specified position of a number. The numbering starts from 0. The least significant digit of a number is 0-th digit. For example 0th digit of 2341238 is 8 and 3-rd digit is 1.

#include <stdio.h>
#include <math.h>

/*Function to return the digit of n-th position of num. Position starts from 0*/
int getdigit(int num, int n)
{
    int r, t1, t2;

    t1 = pow(10, n+1);
    r = num % t1;

    if (n > 0)
    {
        t2 = pow(10, n);
        r = r / t2;
    }

    return r;
}

void main()
{
    int num = 0, pos;

    printf("Enter an integer: ");
    scanf("%d", &num);

    printf("Enter a position: ");
    scanf("%d", &pos);

    printf("%dth digit of %d is %d.\n", pos, num, getdigit(num, pos));
}

Output: (Position starts from 0).
Enter an integer: 345672
Enter a position: 3
3th digit of 345672 is 5.

The post C Program to Get a Digit of Any Position of a Number appeared first on QnA Plus.

C Program Insert Element in a Singly Linked List

$
0
0

Following C programs show how to insert elements in a singly linked list, at the front, end or a specified location.
Insert at the front of the list

#include <stdio.h>
#include <stdlib.h>

struct node{
    int val;
    struct node *next;
};

void print_list(struct node *head)
{
    printf("H->");

    while(head)
    {
        printf("%d->", head->val);
        head = head->next;
    }

    printf("|||\n");
}

void insert_front(struct node **head, int value)
{
    struct node * new_node = NULL;

    new_node = (struct node *)malloc(sizeof(struct node));

    if (new_node == NULL)
    {
        printf("Failed to insert element. Out of memory");
    }

    new_node->val = value;
    new_node->next = *head;

    *head = new_node;
}

void main()
{
    int count = 0, i, val;
    struct node * head = NULL;

    printf("Enter number of elements: ");
    scanf("%d", &count);

    for (i = 0; i < count; i++)
    {
        printf("Enter %dth element: ", i);
        scanf("%d", &val);
        insert_front(&head, val);
    }

    printf("Initial List: ");
    print_list(head);

    printf("Enter a value to enter at the front of the list: ");
    scanf("%d", &val);
    insert_front(&head, val);

    printf("List after insertion: ");
    print_list(head);
}

Output:

Enter number of elements: 5
Enter 0th element: 4
Enter 1th element: 53
Enter 2th element: 56
Enter 3th element: 76
Enter 4th element: 34
Initial List: H->34->76->56->53->4->|||
Enter a value to enter at the front of the list: 10
List after insertion: H->10->34->76->56->53->4->|||

Insert at the end of the list

#include <stdio.h>
#include <stdlib.h>

struct node{
    int val;
    struct node *next;
};

void print_list(struct node *head)
{
    printf("H->");

    while(head)
    {
        printf("%d->", head->val);
        head = head->next;
    }

    printf("|||\n");
}

void insert_front(struct node **head, int value)
{
    struct node * new_node = NULL;

    new_node = (struct node *)malloc(sizeof(struct node));

    if (new_node == NULL)
    {
        printf("Failed to insert element. Out of memory");
    }

    new_node->val = value;
    new_node->next = *head;

    *head = new_node;
}

void insert_end(struct node **head, int value)
{
    struct node * new_node = NULL;
    struct node * last = NULL;

    new_node = (struct node *)malloc(sizeof(struct node));

    if (new_node == NULL)
    {
        printf("Failed to insert element. Out of memory");
    }

    new_node->val = value;
    new_node->next = NULL;

    if( *head == NULL)
    {
        *head = new_node;
        return;
    }

    last = *head;
    while(last->next) last = last->next;

    last->next = new_node;
}

void main()
{
    int count = 0, i, val;
    struct node * head = NULL;

    printf("Enter number of elements: ");
    scanf("%d", &count);

    for (i = 0; i < count; i++)
    {
        printf("Enter %dth element: ", i);
        scanf("%d", &val);
        insert_front(&head, val);
    }

    printf("Initial List: ");
    print_list(head);

    printf("Enter a value to enter at the end of the list: ");
    scanf("%d", &val);
    insert_end(&head, val);

    printf("List after insertion: ");
    print_list(head);
}

Output:

Enter number of elements: 5
Enter 0th element: 6
Enter 1th element: 56
Enter 2th element: 34
Enter 3th element: 4
Enter 4th element: 56
Initial List: H->56->4->34->56->6->|||
Enter a value to enter at the front of the list: 10
List after insertion: H->56->4->34->56->6->10->|||

Insert an element after a specified node.

#include <stdio.h>
#include <stdlib.h>

struct node{
    int val;
    struct node *next;
};

struct node * find_node(struct node *head, int val)
{
    struct node *tmp = head;

    while(tmp)
    {
        if (tmp->val == val) return tmp; /*Found*/

        tmp = tmp->next;
    }

    return NULL; /*Not found*/
}

void print_list(struct node *head)
{
    printf("H->");

    while(head)
    {
        printf("%d->", head->val);
        head = head->next;
    }

    printf("|||\n");
}

void insert_front(struct node **head, int value)
{
    struct node * new_node = NULL;

    new_node = (struct node *)malloc(sizeof(struct node));

    if (new_node == NULL)
    {
        printf("Failed to insert element. Out of memory");
    }

    new_node->val = value;
    new_node->next = *head;

    *head = new_node;
}

void insert_after(struct node *pos, int value)
{
    struct node * new_node = NULL;

    if (pos == NULL) return;

    new_node = (struct node *)malloc(sizeof(struct node));

    if (new_node == NULL)
    {
        printf("Failed to insert element. Out of memory");
    }

    new_node->val = value;
    new_node->next = pos->next;
    pos->next = new_node;
}

void main()
{
    int count = 0, i, val, pos;
    struct node * head = NULL;

    printf("Enter number of elements: ");
    scanf("%d", &count);

    for (i = 0; i < count; i++)
    {
        printf("Enter %dth element: ", i);
        scanf("%d", &val);
        insert_front(&head, val);
    }

    printf("Initial List: ");
    print_list(head);

    printf("Enter a value to insert in the list: ");
    scanf("%d", &val);

    printf("Insert after: ");
    scanf("%d", &pos);

    insert_after(find_node(head, pos), val);

    printf("List after insertion: ");
    print_list(head);
}

Output:

Enter number of elements: 5
Enter 0th element: 34
Enter 1th element: 53
Enter 2th element: 5
Enter 3th element: 6
Enter 4th element: 34
Initial List: H->34->6->5->53->34->|||
Enter a value to insert in the list: 10
Insert after: 6
List after insertion: H->34->6->10->5->53->34->|||

Insert an element before a specified node.

#include <stdio.h>
#include <stdlib.h>

struct node{
    int val;
    struct node *next;
};

struct node * find_node(struct node *head, int val)
{
    struct node *tmp = head;

    while(tmp)
    {
        if (tmp->val == val) return tmp; /*Found*/

        tmp = tmp->next;
    }

    return NULL; /*Not found*/
}

void print_list(struct node *head)
{
    printf("H->");

    while(head)
    {
        printf("%d->", head->val);
        head = head->next;
    }

    printf("|||\n");
}

void insert_front(struct node **head, int value)
{
    struct node * new_node = NULL;

    new_node = (struct node *)malloc(sizeof(struct node));

    if (new_node == NULL)
    {
        printf("Failed to insert element. Out of memory");
    }

    new_node->val = value;
    new_node->next = *head;

    *head = new_node;
}

void insert_before(struct node **head, struct node *pos, int value)
{
    struct node * new_node = NULL;
    struct node * tmp_node = NULL;

    if (pos == NULL) return;

    new_node = (struct node *)malloc(sizeof(struct node));

    if (new_node == NULL)
    {
        printf("Failed to insert element. Out of memory");
    }

    new_node->val = value;

    if(*head == pos)
    {
        new_node->next = pos;
        *head = new_node;
        return;
    }

    tmp_node = *head;

    while(tmp_node->next != pos)
    {
        tmp_node = tmp_node->next;

        if(tmp_node == NULL) return; /*Not found*/
    }

    new_node->next = tmp_node->next;
    tmp_node->next = new_node;
}

void main()
{
    int count = 0, i, val, pos;
    struct node * head = NULL;

    printf("Enter number of elements: ");
    scanf("%d", &count);

    for (i = 0; i < count; i++)
    {
        printf("Enter %dth element: ", i);
        scanf("%d", &val);
        insert_front(&head, val);
    }

    printf("Initial List: ");
    print_list(head);

    printf("Enter a value to insert in the list: ");
    scanf("%d", &val);

    printf("Insert before: ");
    scanf("%d", &pos);

    insert_before(&head, find_node(head, pos), val);

    printf("List after insertion: ");
    print_list(head);
}

Output:

Enter number of elements: 5
Enter 0th element: 43
Enter 1th element: 45
Enter 2th element: 43
Enter 3th element: 2
Enter 4th element: 67
Initial List: H->67->2->43->45->43->|||
Enter a value to insert in the list: 10
Insert before: 2
List after insertion: H->67->10->2->43->45->43->|||

The post C Program Insert Element in a Singly Linked List appeared first on QnA Plus.

Delete an element from a singly linked list

$
0
0

Here is the C program to delete an element from a singly linked list.

#include 
#include 

struct node{
    int val;
    struct node *next;
};

struct node * find_node(struct node *head, int val)
{
    struct node *tmp = head;

    while(tmp)
    {
        if (tmp->val == val) return tmp; /*Found*/

        tmp = tmp->next;
    }

    return NULL; /*Not found*/
}

void print_list(struct node *head)
{
    printf("H->");

    while(head)
    {
        printf("%d->", head->val);
        head = head->next;
    }

    printf("|||\n");
}

void insert_front(struct node **head, int value)
{
    struct node * new_node = NULL;

    new_node = (struct node *)malloc(sizeof(struct node));

    if (new_node == NULL)
    {
        printf("Failed to insert element. Out of memory");
    }

    new_node->val = value;
    new_node->next = *head;

    *head = new_node;
}

void delete_elem(struct node **head, int val)
{
    struct node * del = find_node(*head, val);
    struct node * tmp = NULL;

    if (del == NULL) return;

    if (*head == del)
    {
        *head = del->next;
    }
    else
    {
        tmp = *head;

        while(tmp->next != del) tmp = tmp->next;

        tmp->next = del->next;
    }

    free(del);
}

void main()
{
    int count = 0, i, val;
    struct node * head = NULL;

    printf("Enter number of elements: ");
    scanf("%d", &count);

    for (i = 0; i < count; i++)
    {
        printf("Enter %dth element: ", i);
        scanf("%d", &val);
        insert_front(&head, val);
    }

    printf("Initial List: ");
    print_list(head);

    printf("Enter a value to delete from the list: ");
    scanf("%d", &val);

    delete_elem(&head, val);

    printf("List after deletion: ");
    print_list(head);
}

Output:

Enter number of elements: 5
Enter 0th element: 43
Enter 1th element: 5
Enter 2th element: 10
Enter 3th element: 23
Enter 4th element: 78
Initial List: H->78->23->10->5->43->|||
Enter a value to delete from the list: 10
List after deletion: H->78->23->5->43->|||

The post Delete an element from a singly linked list appeared first on QnA Plus.


C Program to Check Whether a Number is Odd or Even

$
0
0

Check odd or even using modulus operator
Even numbers are always divisible by 2. If you do the modulo operation on the given number with 2 and the reminder is 0,then the number is even, otherwise, odd. This principle is applied in the following program.

#include <stdio.h>

void main()
{
    int num = 0;

    printf("Enter an integer: ");
    scanf("%d", &num);

    if (num%2 == 0)
    {
        printf("%d is an even number.\n", num);
    }
    else
    {
        printf("%d is an odd number.\n", num);
    }
}

C program to check odd or even using bitwise operator
The least significant bit of an even number is always 0. Similar thing applied for the odd numbers. Least significant bit of an odd number is always 1. If you do bitwise AND operation between the given number and 1 and the result becomes 0, then the least significant bit of the number is 0. That means the number is even. Similarly, if the result becomes 1, the number is odd. This principle is applied in the following program.

#include <stdio.h>

void main()
{
    int num = 0;

    printf("Enter an integer: ");
    scanf("%d", &num);

    if (num & 1 == 0)
    {
        printf("%d is an even number.\n", num);
    }
    else
    {
        printf("%d is an odd number.\n", num);
    }
}

C program to check odd or even without using bitwise or modulus operator

#include <stdio.h>
void main()
{
    int num = 0;

    printf("Enter an integer: ");
    scanf("%d", &num);

    if ((n/2)*2 == n)
    {
        printf("%d is an even number.\n", num);
    }
    else
    {
        printf("%d is an odd number.\n", num);
    }
}

Output:

Enter an integer: 234
234 is an event number.

Enter an integer: 2231
2231 is an odd number.

The post C Program to Check Whether a Number is Odd or Even appeared first on QnA Plus.

Insert an Element in a Sorted Singly Linked List

$
0
0

Sorted Linked List is a linked list where the elements are always sorted. Insert operation in a singly is bit tricky. You have to insert an element such a way that the list remains sorted after insertion. The insertion logic is:

  1. If the list is empty or the value of the element (to be inserted) is less than the value of head, insert the element at the front of the list.
  2. Otherwise, traverse the list in this way: for a particular node of the list, if the next pointer is NULL (end of list) or the value of the element (to be inserted) is less than the value of the next node, insert the element after the current node, or move to the next node.

#include <stdio.h>
#include <stdlib.h>

struct node{
    int val;
    struct node *next;
};

void print_list(struct node *head)
{
    printf("H->");

    while(head)
    {
        printf("%d->", head->val);
        head = head->next;
    }

    printf("|||\n");
}

void insert_sorted(struct node **head, int value)
{
    struct node * new_node = NULL;
    struct node * tmp_node = NULL;

    new_node = (struct node *)malloc(sizeof(struct node));

    if (new_node == NULL)
    {
        printf("Failed to insert element. Out of memory");
    }

    new_node->val = value;

    if(*head == NULL || value < (*head)->val)
    {
        new_node->next = *head;
        *head = new_node;
        return;
    }

    tmp_node = *head;

    while(tmp_node->next && value > tmp_node->next->val)
    {
        tmp_node = tmp_node->next;
    }

    new_node->next = tmp_node->next;
    tmp_node->next = new_node;
}

void main()
{
    int count = 0, i, val;
    struct node * head = NULL;

    printf("Enter number of elements: ");
    scanf("%d", &count);

    for (i = 0; i < count; i++)
    {
        printf("Enter %dth element: ", i);
        scanf("%d", &val);
        insert_sorted(&head, val);
    }

    printf("List after insertion: ");
    print_list(head);
}

Output:

Enter number of elements: 10
Enter 0th element: 6
Enter 1th element: 34
Enter 2th element: 5
Enter 3th element: 90
Enter 4th element: 65
Enter 5th element: 78
Enter 6th element: 65
Enter 7th element: 34
Enter 8th element: 23
Enter 9th element: 88
List after insertion: H->5->6->23->34->34->65->65->78->88->90->|||

The post Insert an Element in a Sorted Singly Linked List appeared first on QnA Plus.

C Program to Convert Binary Number to Decimal

$
0
0

Binary number system is 2-based which means at most two symbols, 0 (zero) and 1 (one), can be used to represent a binary number. Example of binary number is 110110011, sometimes binary numbers are written as 1101100112, where 2 is represented as base of the number system. Binary number system is the basis of all computer and digital systems. All information in computer and digital system are internally represented as binary number.

In contrast, decimal number system is 10-based that means at most 10 symbols (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) can be used to represent a decimal number. Example of decimal number is 435, sometimes written as 43510 which is same as binary 1101100112. Most of the time we use binary number system.

Binary Number to decimal conversion

There is common rule for conversion from any number system to decimal. Mathematical description of the rule is:

Numberb = (dN…d3d2d1d0)b = (dNxbN + … + d3xb3 + d2xb2 + d1xb1 + d0xb0)10

Where,
Numberb is the number of a number system with base b.
dN is the digit of N-th position starting from right.

This expression might appear too complex. If we can have one example, this will look easier. We’ll see how we can get 43510 from 1101100112.

Here our number id 1101100112, base is 2. The number has 9 digits. So, d8 = 1, d7 = 1, d6 = 0, d5 = 1, d4 = 1, d3 = 0, d2 = 0, d1 = 1, d0 = 1.

So the decimal equivalent is (1.28 + 1.27 + 0.26 + 1.25 + 1.24 + 0.23 + 0.22 + 1.21 + 1.20)10 = (256 + 128 + 0 + 32 + 16 + 0 + 0 + 2 + 1)10 = 43510.

C Program

C program that takes a binary number as input and prints the equivalent decimal number.

#include <stdio.h>

void main()
{
    unsigned long bin;
    unsigned ling decimal = 0;

    int i = 1, r;

    printf("Enter binary: ");
    scanf("%lu", &bin);

    while(bin)
    {
        r = bin % 10;
        if (r > 1)
        {
            printf("Not binary!\n");
            return;
        }
        decimal += r * i;

        i *= 2;
        bin = bin / 10;
    }

    printf("%lu in decimal.\n", decimal);
}

Outout:

Enter binary: 101001
41 in decimal.

Explanation:
Logic of the program is exactly what is explained in the previous section. The program takes the binary number as user input and saves that in an unsigned long integer bin. The while loop iterates as many time as the number of digits in the input binary nummber. If the input number is 101001 then the while loop will iterate 6 times. How? consider the line bin = bin / 10. It will remove last digit in every iteration from bin. After first iteration bin will become 10100 and in next iteration it will become 1010 and after 6 iterations it will become 0. The the while(bin) condition will break. The variable decimal starts with 0 and in every iteration (say iteration number n, starting with 0) dn.2n will be added. Because i starts with 1 (20), in next iteration it will become 2 (21), then 4 (22) and so on. Similarly, r will be the last digit of the input in first iteration, second last in second iteration, third last in third iteration and so on.

The post C Program to Convert Binary Number to Decimal appeared first on QnA Plus.

C Program to Sort Linked List without Allocating Extra Memory

$
0
0

We’ll first create a linked list which is not sorted, then we’ll re-arrange the list such that the list becomes sorted.

Logic is simple, we’ll iterate the list for all nodes, in every iteration we’ll take the first node out of the original list and insert that node into a new list. At any point of time the new list is sorted, and we’ll insert a new node in the new list such a way that new list remains sorted.

It is demonstrated graphically.

Linked list sorting

 

#include <stdio.h>
#include <stdlib.h>

struct node{
    int val;
    struct node *next;
};

void print_list(struct node *head)
{
    printf("H->");

    while(head)
    {
        printf("%d->", head->val);
        head = head->next;
    }

    printf("|||\n");
}

void insert_front(struct node **head, int value)
{
    struct node * new_node = NULL;

    new_node = (struct node *)malloc(sizeof(struct node));

    if (new_node == NULL)
    {
        printf("Failed to insert element. Out of memory");
    }

    new_node->val = value;
    new_node->next = *head;

    *head = new_node;
}

void insert_sorted(struct node **head, struct node *new_node)
{
    struct node *tmp_node = NULL;

    if(*head == NULL || new_node->val < (*head)->val)
    {
        new_node->next = *head;
        *head = new_node;
        return;
    }

        tmp_node = *head;

    while(tmp_node->next && new_node->val > tmp_node->next->val)
    {
        tmp_node = tmp_node->next;
    }

    new_node->next = tmp_node->next;
    tmp_node->next = new_node;
}

void sort_list(struct node **head)
{
    struct node *new_head = NULL;
    struct node *tmp = *head;
    struct node *tmp1 = NULL;

    while(tmp)
    {
        tmp1 = tmp;
        tmp = tmp->next;

        insert_sorted(&new_head, tmp1);
    }

    *head = new_head;
}

void main()
{
    int count = 0, i, val;
    struct node * head = NULL;

    printf("Enter number of elements: ");
    scanf("%d", &count);

    for (i = 0; i < count; i++)
    {
        printf("Enter %dth element: ", i);
        scanf("%d", &val);
        insert_front(&head, val);
    }

    printf("Link list before sorting: ");
    print_list(head);

    sort_list(&head);

    printf("Sorted linked list: ");
    print_list(head);
}

Output:

Enter number of elements: 5
Enter 0th element: 10
Enter 1th element: 6
Enter 2th element: 18
Enter 3th element: 9
Enter 4th element: 24
Link list before sorting: H->24->9->18->6->10->|||
Sorted linked list: H->6->9->10->18->24->|||

The logic described above is implemented in this program. The sort_list() function takes the first node out of the original list and passes that to the insert_sorted() function. The insert_sorted() places the node in the new list such that the list remains sorted. This is like insertion sort, at any moment, a portion of the list will be sorted. And in every iteration, a new node will be inserted into the sorted portion such that the sorted portion remains sorted with one more node.

The post C Program to Sort Linked List without Allocating Extra Memory appeared first on QnA Plus.

Loop in Linked List, C Program to Detect and Remove

$
0
0

What is loop in linked list?

Loop in linked list means you can traverse the list endlessly. If you traverse a linked list with loop, you will hit all or some of the nodes again and again. We’ll see how this is possible.

Linked list without loop
Consider the normal (without loop) linked list above. Head points to the first node (24) and the last node (10) points to NULL. If you traverse this list starting from the head, traversal will end at node 10 because node 10 does not point to any other node. But this will not be the case of linked list with loop.

Loop in linked list
Consider the linked list with a loop above. This linked list is similar to the first one but the last node (10) here is pointing to another node (9), instead of pointing to NULL. If you traverse this list, traversal will never end. The nodes 9, 18, 6, 10 will come again and again.

In the following sections we’ll see how to write C program to detect such loop and remove from the list.

Create the linked list

First we’ll create a normal linked list by inserting nodes at the front of the list.

struct node{
 int val;
 struct node *next;
};

void print_list(struct node *head)
{
 printf("H->");

 while(head)
 {
 printf("%d->", head->val);
 head = head->next;
 }

 printf("|||\n");
}

void insert_front(struct node **head, int value)
{
 struct node * new_node = NULL;

 new_node = (struct node *)malloc(sizeof(struct node));

 if (new_node == NULL)
 {
 printf("Failed to insert element. Out of memory");
 }

 new_node->val = value;
 new_node->next = *head;

 *head = new_node;
}

Read also:

We have a print_list() function here. The output of these functions will be:

Enter number of elements: 5
Enter 0th element: 10
Enter 1th element: 6
Enter 2th element: 18
Enter 3th element: 9
Enter 4th element: 24
Original List: H->24->9->18->6->10->|||

Create the loop

Function to create a loop in the above linked list.

void create_loop(struct node *head)
{
 struct node *tmp = head;

 while(tmp->next) tmp = tmp->next;

 tmp->next = head->next;
}

This function first finds the last node (which points to NULL) of the list and then points the last node to the second node of the list.
How to prove that this function will create loop? Well, after calling this function, we’ll print the list. But wait. If you use the above print_list() function to print the list, the function will fall in an infinite loop. So we’ll slightly modify the print function to print at most 25 nodes.

void print_loop(struct node *head)
{
    int n = 25;
    printf("H->");

    while(n--)
    {
        printf("%d->", head->val);
        head = head->next;
    }

    printf("|||\n");
}

Output of the function will be:

H->24->9->18->6->10->9->18->6->10->9->18->6->10->9->18->6->10->9->18->6->10->9->18->6->10->|||

Here you can see, the nodes 9, 18, 6, 10 are coming again and again.

Function to detect loop in linked list

void detect_loop(struct node *head)
{
    struct node *slow = head;
    struct node *fast = head;

    while(slow && fast->next && fast->next->next)
    {
        if ((slow == fast->next) || (slow == fast->next->next ))
        {
            printf("Linked list has a loop.\n");
            return;
        }

        slow = slow->next;
        fast = fast->next->next;
    }

    printf("Linked list does not have any loop.\n");
}

This function detects loop with the help of two pointers slow and fast. Both slow and fast will start from head and in every iteration slow will move one position and fast will move two positions. In any iteration, if slow or fast->next or fast->next->next becomes NULL, that means there is no loop in the linked list. And if fast->next or fast->next->next becomes equal to slow, that means the linked list has a loop.

Function to remove loop from linked list

Removing loop from linked list is simple; assign the last node to NULL. If no node points to NULL, the which one is the last? Well, in a linked list with loop, there will be one node which will be pointed by two nodes; one of them is the last node. Which one? The one whose distance from head is more.

Here is the function to remove loop:

void remove_loop(struct node *head)
{
    struct node *slow = head;
    struct node *fast = head;

    while(slow && fast->next && fast->next->next)
    {
        if (slow == fast->next)
        {
            fast->next = NULL;
            break;
        }

        if (slow == fast->next->next)
        {
            fast->next->next = NULL;
            break;
        }

        slow = slow->next;
        fast = fast->next->next;
    }
}

The complete program

The complete program is copied here to compile and run.

#include <stdio.h>
#include <stdlib.h>

struct node{
    int val;
    struct node *next;
};

void print_list(struct node *head)
{
    printf("H->");

    while(head)
    {
        printf("%d->", head->val);
        head = head->next;
    }

    printf("|||\n");
}

void insert_front(struct node **head, int value)
{
    struct node * new_node = NULL;

    new_node = (struct node *)malloc(sizeof(struct node));

    if (new_node == NULL)
    {
        printf("Failed to insert element. Out of memory");
    }

    new_node->val = value;
    new_node->next = *head;

    *head = new_node;
}

void create_loop(struct node *head)
{
    struct node *tmp = head;

    while(tmp->next) tmp = tmp->next;

    tmp->next = head->next;
}

void print_loop(struct node *head)
{
    int n = 25;
    printf("H->");

    while(n--)
    {
        printf("%d->", head->val);
        head = head->next;
    }

    printf("|||\n");
}

void detect_loop(struct node *head)
{
    struct node *slow = head;
    struct node *fast = head;

    while(slow && fast->next && fast->next->next)
    {
        if ((slow == fast->next) || (slow == fast->next->next ))
        {
            printf("Linked list has a loop.\n");
            return;
        }

        slow = slow->next;
        fast = fast->next->next;
    }

    printf("Linked list does not have any loop.\n");
}

void remove_loop(struct node *head)
{
    struct node *slow = head;
    struct node *fast = head;

    while(slow && fast->next && fast->next->next)
    {
    if (slow == fast->next)
    {
        fast->next = NULL;
        break;
    }

    if (slow == fast->next->next)
    {
        fast->next->next = NULL;
        break;
    }

    slow = slow->next;
    fast = fast->next->next;
    }
}

void main()
{
    int count = 0, i, val;
    struct node * head = NULL;

    printf("Enter number of elements: ");
    scanf("%d", &count);

    for (i = 0; i < count; i++)
    {
        printf("Enter %dth element: ", i);
        scanf("%d", &val);
        insert_front(&head, val);
    }

    printf("Original List: ");
    print_list(head);
    detect_loop(head);

    create_loop(head);
    print_loop(head);
    detect_loop(head);

    printf("Removing loop...\n");
    remove_loop(head);
    detect_loop(head);
}

Output:

Enter number of elements: 5
Enter 0th element: 10
Enter 1th element: 6
Enter 2th element: 18
Enter 3th element: 9
Enter 4th element: 24
Original List: H->24->9->18->6->10->|||
Linked list does not have any loop.
H->24->9->18->6->10->9->18->6->10->9->18->6->10->9->18->6->10->9->18->6->10->9->18->6->10->|||
Linked list has a loop.
Removing loop...
Linked list does not have any loop.

The post Loop in Linked List, C Program to Detect and Remove appeared first on QnA Plus.

How to Implement Periodic Timer in Linux

$
0
0

In this article we’ll see how to implement periodic timer in Linux using C programming language. We’ll first create a timer library that will be used to create one or more timers. Timers can be periodic or single shot. You’ll be able to use this timer library in your own program to create one or multiple timers.

Click here to download the complete program with Makefile.

The Timer Header File

We’ll start with the header file of the timer module. The following header file, mytimer.h, displays the functions and data structures that can be used by other programs to create periodic or single shot timers.

/*mytimer.h*/
#ifndef TIME_H
#define TIME_H
#include <stdlib.h>

typedef enum
{
TIMER_SINGLE_SHOT = 0, /*Periodic Timer*/
TIMER_PERIODIC         /*Single Shot Timer*/
} t_timer;

typedef void (*time_handler)(size_t timer_id, void * user_data);

int initialize();
size_t start_timer(unsigned int interval, time_handler handler, t_timer type, void * user_data);
void stop_timer(size_t timer_id);
void finalize();

#endif

In the header file, there are four functions.

  • initialize(): The user of this timer library has to call this function before using any other function. This function should be called only once, no matter how many timers you want to create.
  • start_timer(): This function is used to create a timer. It returns the timer id that would be used in stop_timer() function. It has the following input parameters.
    • interval: Timeout interval in seconds. If the value of interval is 10, the timer will be expired (will call callback function) after 10 seconds. And in case of periodic timer, the timer will keep expiring after every 10 seconds.
    • handler: The call back function. After expiry of the timer, this callback function will be called.
    • type: This specifies whether the timer is periodic or single shot. The value of type could be TIMER_PERIODIC or TIMER_SINGLE_SHOT.
    • user_data: User of the library can specify any data in form of void pointer that would be passed in the callback function in timer expiry.
  • stop_timer(): This function is used to stop a particular timer. It takes the timer id as input. It stops the timer specified by the timer id. Timer id is returned by the start_timer() function in time of creating the timer.
  • finalize(): The function should be called when the timer module is no longer required. It stops (and deletes) all running timers.

Before going into the actual implementation of these functions, we’ll see how you can use these functions to implement periodic and single shot timer in the following example program.

Example Program

In this example program, three timers are created. One single shot timer which will expire after 20 seconds. Two periodic timers, one will expire in every 10 seconds and other in every 5 seconds.

#include <stdio.h>
#include <stdlib.h>

#include "mytimer.h"

void time_handler1(size_t timer_id, void * user_data)
{
    printf("Single shot timer expired.(%d)\n", timer_id);
}

void time_handler2(size_t timer_id, void * user_data)
{
    printf("10 sec timer expired. (%d)\n", timer_id);
}

void time_handler3(size_t timer_id, void * user_data)
{
    printf("5 sec timer expired. (%d)\n", timer_id);
}

void main()
{
    size_t timer1, timer2, timer3;

    initialize();

    timer1 = start_timer(20, time_handler1, TIMER_SINGLE_SHOT, NULL);
    timer2 = start_timer(10, time_handler2, TIMER_PERIODIC, NULL);
    timer3 = start_timer(5, time_handler3, TIMER_PERIODIC, NULL);

    sleep(60);

    stop_timer(timer1);
    stop_timer(timer2);
    stop_timer(timer3);

    finalize();
}

In this program, we have three functions time_handler1(), time_handler2() and timer_handler3() for three timers. These functions will be used as callback functions. As we discussed earlier that before calling any timer function, initialize() needs to be called to make the timer module ready. That we did in line number 25.

In next three lines, we started 3 timers. First timer is the single shot one. In the first parameter is the time out value which is 20 seconds. The next parameter is the function pointer that would be called in timer expiry. The 3rd parameter specifies that the timer is single shot with the constant TIMER_SINGLE_SHOT. The next two timer_start() functions are similar. We specified timeout values 10 and 5 seconds respectively. To make the timers periodic, we used TIMER_PERIODIC constant as 3rd parameter.

Then we simply waits for 60 seconds before stopping all the timers and finalizing the timer module.

Output of the above program is shown below:

5 sec timer expired. (28524944)
5 sec timer expired. (28524944)
10 sec timer expired. (28524896)
5 sec timer expired. (28524944)
5 sec timer expired. (28524944)
10 sec timer expired. (28524896)
Single shot timer expired.(28524848)
5 sec timer expired. (28524944)
5 sec timer expired. (28524944)
10 sec timer expired. (28524896)
5 sec timer expired. (28524944)
5 sec timer expired. (28524944)
10 sec timer expired. (28524896)
5 sec timer expired. (28524944)
5 sec timer expired. (28524944)
10 sec timer expired. (28524896)

Implementation of the Timer Library

Here is the implementation of the timer library functions. This library internally uses the timerfd system calls.

/*mytimer.c*/

#include <stdint.h>
#include <string.h>
#include <sys/timerfd.h>
#include <pthread.h>
#include <poll.h>
#include <stdio.h>

#include "mytimer.h"

#define MAX_TIMER_COUNT 1000

struct timer_node
{
    int                 fd;
    time_handler        callback;
    void *              user_data;
    unsigned int        interval;
    t_timer             type;
    struct timer_node * next;
};

static void * _timer_thread(void * data);
static pthread_t g_thread_id;
static struct timer_node *g_head = NULL;

int initialize()
{
    if(pthread_create(&g_thread_id, NULL, _timer_thread, NULL))
    {
        /*Thread creation failed*/
        return 0;
    }

    return 1;
}

size_t start_timer(unsigned int interval, time_handler handler, t_timer type, void * user_data)
{
    struct timer_node * new_node = NULL;
    struct itimerspec new_value;

    new_node = (struct timer_node *)malloc(sizeof(struct timer_node));

    if(new_node == NULL) return 0;

    new_node->callback  = handler;
    new_node->user_data = user_data;
    new_node->interval  = interval;
    new_node->type      = type;

    new_node->fd = timerfd_create(CLOCK_REALTIME, 0);

    if (new_node->fd == -1)
    {
        free(new_node);
        return 0;
    }

    new_value.it_value.tv_sec  = interval;
    new_value.it_value.tv_nsec = 0;

    if (type == TIMER_PERIODIC)
    {
        new_value.it_interval.tv_sec = interval;
    }
    else
    {
        new_value.it_interval.tv_sec = 0;
    }
    
    new_value.it_interval.tv_nsec = 0;

    timerfd_settime(new_node->fd, 0, &new_value, NULL);

    /*Inserting the timer node into the list*/
    new_node->next = g_head;
    g_head = new_node;

    return (size_t)new_node;
}

void stop_timer(size_t timer_id)
{
    struct timer_node * tmp = NULL;
    struct timer_node * node = (struct timer_node *)timer_id;

    if (node == NULL) return;

    close(node->fd);

    if(node == g_head)
    {
        g_head = g_head->next;
    }

    tmp = g_head;

    while(tmp && tmp->next != node) tmp = tmp->next;

    if(tmp && tmp->next)
    {
        tmp->next = tmp->next->next;
    }

    if(node) free(node);
}

void finalize()
{
    while(g_head) stop_timer((size_t)g_head);

    pthread_cancel(g_thread_id);
    pthread_join(g_thread_id, NULL);
}

struct timer_node * _get_timer_from_fd(int fd)
{
    struct timer_node * tmp = g_head;

    while(tmp)
    {
        if(tmp->fd == fd) return tmp;

        tmp = tmp->next;
    }
    return NULL;
}

void * _timer_thread(void * data)
{
    struct pollfd ufds[MAX_TIMER_COUNT] = {{0}};
    int iMaxCount = 0;
    struct timer_node * tmp = NULL;
    int read_fds = 0, i, s;
    uint64_t exp;

    while(1)
    {
        pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
        pthread_testcancel();
        pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);

        iMaxCount = 0;
        tmp = g_head;

        memset(ufds, 0, sizeof(struct pollfd)*MAX_TIMER_COUNT);
        while(tmp)
        {
            ufds[iMaxCount].fd = tmp->fd;
            ufds[iMaxCount].events = POLLIN;
            iMaxCount++;

            tmp = tmp->next;
        }
        read_fds = poll(ufds, iMaxCount, 100);

        if (read_fds <= 0) continue;

        if (read_fds <= 0) continue;

        for (i = 0; i < iMaxCount; i++)
        {
            if (ufds[i].revents & POLLIN)
            {
                s = read(ufds[i].fd, &exp, sizeof(uint64_t));

                if (s != sizeof(uint64_t)) continue;

                tmp = _get_timer_from_fd(ufds[i].fd);

                if(tmp && tmp->callback) tmp->callback((size_t)tmp, tmp->user_data);
            }
        }
    }

    return NULL;
}

We’ll briefly discuss about the timerfd system calls to understand this code. The timerfd_create() function is used create a timer. This function returns an fd (file descriptor) which will be used to start or monitor the timer. The timerfd_settime() function is used to start the timer. We can also specify whether the timer is periodic or single shot. If one or more timer expirations have occurred, then the corresponding file descriptors (fd) will be readable using read() system call. Our strategy is to have one thread that will continuously check all file descriptors (fd) using poll() system call. If any file descriptor is set (POLLIN) then we’ll call the callback function of the corresponding timer.
The data structure, timer_node, is declared in line 14 to store all information related to a timer. As we maintain multiple timers in this library, we store the timer contexts in a linked list. The head of the linked list, g_head, is defined in line 26.
Function definitions:

  • initialize(): This function creates a thread that will monitor all timers to check whether any timer is expired. It stores the thread id in g_thread_id which will be used to stop the thread.
  • start_timer(): This function creates and starts a timer. It first allocates memory (new_node) for the new timer. It stores all relavent information such as callback function, interval, type (periodic or single shot) of the timer in the new_node structure. Then it create the timer using timerfd_create() function and stores the returned fd (file descriptor) in new_node. Time out interval is set in new_value.it_value.tv_sec variable and in case of periodic timer the interval is set in new_value.it_interval.tv_sec variable also. Then it starts the timer using timerfd_settime() function. At the end it inserts the timer structure (new_node) in the linked list.
  • stop_timer(): This function stops the timer using close() system call using the file descriptor (fd) of the timer. Then the timer data structure is removed from the linked list.
  • finalize(): This function should be called when the timer module is no longer required. It first stops all running timers, if any, and then stops the thread.
  • _timer_thread(): It continuously checks if any timer file descriptor (fd) is set using poll() system call. If any timer file descriptor is set and readable using read() system call, then calls the callback function of the timer with timer id and user_data.

Read also: How to implement periodic timer in Linux kernel.

The post How to Implement Periodic Timer in Linux appeared first on QnA Plus.

How to Access MySQL Database from C Program?

$
0
0

MySQL is an open sourcce database management system (DBMS). It is very popular among the web developers as it is part of LAMP (Linux, Apache, MySQL, PHP/Perl/Python) stack. Many popular large scale websites like WikiPedia, Facebook, Youtube use this database. Many times we need to use access MySQL database from C program. Here we’ll see how to access MySQL database from C program

Note: CentOS 7.2 operating system is used here for database installation and code compilation. These should be same for all RedHat based Linux distributions.

Installing MySql

If you already have MySQL installed on your system, then you can skip this section and use the existing database, otherwise, issue the following commands to install MySQL database.

Please note that you have to be super user (root) and need to have internet connection while issues these commands.

wget http://repo.mysql.com/mysql-community-release-el7-5.noarch.rpm
rpm -ivh mysql-community-release-el7-5.noarch.rpm
yum update
yum install mysql-server

MySQL runs as service on Linux system. To start the MySQL service, issues this command as super user (root)

systemctl start mysqld

You can also check whether the service is really running by this command.

systemctl status mysqld

If the service is running then this command will show active (running) as shown below.
MySQL service running

Creating Table in the Database

In this section, we’ll create a sample table in the MySQL database manually right in the database server. We’ll access that table from C program later.
Login to the database.

mysql -u root -p

Under MySQL, you can have multiple databases. Tables will be created under databases. You can create a new database by issuing this command.

CREATE DATABASE mydb;

Now you have to go inside the database by command.

USE mydb;

Create a table my_table under mydb database using this SQL statement.

CREATE TABLE my_table (table_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, first_name TEXT, last_name TEXT);

Insert some entries to the table my_table.

INSERT INTO my_table(first_name, last_name) VALUES('Cristiano', 'Ronaldo');
INSERT INTO my_table(first_name, last_name) values('Lionel', 'Messi');

You can check the entries of the table by this SQL query.

SELECT * FROM my_table;

Access MySQL database from C Program

To access MySQL database, you need to have the mysql-devel package on you system. This package provides the share libraries and header files required to MySQL client program development. Header files are required for program compilation and shared libraries are used at run-time. To check whether the package is already installed by this command.

yum info mysql-devel

If not installed, issue this command to install mysql-devel.

yum install mysql-devel

Here is the MySQL client program to access database entities like table, rows of tables.

#include <mysql.h>
#include <stdio.h>

int main()
{
 MYSQL *conn;
 MYSQL_RES *res;
 MYSQL_ROW row;

 char *server = "localhost";
 char *user = "root";
 char *password = ""; /*password is not set in this example*/
 char *database = "mydb";

 conn = mysql_init(NULL);

 /* Connect to database */
 if (!mysql_real_connect(conn, server,
 user, password, database, 0, NULL, 0))
 {
   printf("Failed to connect MySQL Server %s. Error: %s\n", server, mysql_error(conn));
   return 0;
 }

 /* Execute SQL query to fetch all table names.*/
 if (mysql_query(conn, "show tables"))
 {
   printf("Failed to execute quesry. Error: %s\n", mysql_error(conn));
   return 0;
 }

 res = mysql_use_result(conn);

 /* Output table name */
 printf("MySQL Tables in mydb database:\n");
 while ((row = mysql_fetch_row(res)) != NULL)
 printf("%s \n", row[0]);

 /* free results */
 mysql_free_result(res);

 /* send SQL query */
 if (mysql_query(conn, "select * from my_table"))
 {
   printf("Failed to execute quesry. Error: %s\n", mysql_error(conn));
   return 0;
 }

 res = mysql_store_result(conn);
 if (res == NULL)
 {
   return 0;
 }

 int columns = mysql_num_fields(res);

 int i = 0;

 printf("Entries in the table my_table:\n");
 while(row = mysql_fetch_row(res))
 {
   for (i = 0; i < columns; i++)
   {
     printf("%s ", row[i] ? row[i] : "NULL");
   }
   printf("\n");
 }

 mysql_free_result(res);
 mysql_close(conn);

 return 1;
}

In our example program above, we display all tables in our mydb database and all rows from the table my_table.

Before doing any database operation, we need to connect to the database server. This portion of the code does that.

conn = mysql_init(NULL);

 /* Connect to database */
 if (!mysql_real_connect(conn, server,
 user, password, database, 0, NULL, 0))
 {
   printf("Failed to connect MySQL Server %s. Error: %s\n", server, mysql_error(conn));
   return 0;
 }

The API mysql_init() initializes one MYSQL object and returns the address (pointer) of that object in case of successful allocation. If the function fails to allocate the MYSQL object, then it returns NULL. The returned pointer would be used as the handle for subsequent database operations. To access any database element like tables or any field of a table, we have to first connect to the database server. The mysql_real_connect() function is used to connect to the MySQL database server. It takes IP address or domain name of the system where the MySQL server is running. As our server is running on the same system where the program will run,  “localhost”
is used as the server domain name. If you want to access database running on a remote machine, you can specify the domain name or IP Address of the remote machine. Also we have to specify user id, password and database name. In our case user id is “root” and database name is “mydb”.

 

/* Execute SQL query to fetch all table names.*/
 if (mysql_query(conn, "show tables"))
 {
   printf("Failed to execute quesry. Error: %s\n", mysql_error(conn));
   return 0;
 }

 res = mysql_use_result(conn);

 /* Output table name */
 printf("MySQL Tables in mydb database:\n");
 while ((row = mysql_fetch_row(res)) != NULL)
 printf("%s \n", row[0]);

 /* free results */
 mysql_free_result(res);

The above piece of code gets all the table names from the connected MySQL database. To do that, we have to run a SQL query which we can do by using mysql_query() API. To get the result of the executed query we have to use either mysql_use_result() or mysql_store_result() API. Here we used mysql_use_result() which does not bring the whole result to the
client side. So we have to call mysql_fetch_row() to fetch one row at a time from the server. If mysql_fetch_row() returns NULL, then there is no more row to be fetched. The “show tables” query will return all table name in a table. So, this while loop will return all available tables and print them. The returned value from the mysql_use_result() needs to be freed by mysql_free_result() API.

Later part of the code fetches all row of the table my_table.

if (mysql_query(conn, "select * from my_table"))
 {
   printf("Failed to execute quesry. Error: %s\n", mysql_error(conn));
   return 0;
 }

 res = mysql_store_result(conn);
 if (res == NULL)
 {
   return 0;
 }

Here also we used mysql_query() API to execute SELECT SQL query. Here we use the mysql_store_result() to fetch all returned row to the client.
In this case mysql_fetch_row() will not bring the row from the server, rather it will return from the res which is available in the memory of the client (our program)

The code below will traverse through all rows and print them.

int columns = mysql_num_fields(res);

 int i = 0;

 printf("Entries in the table my_table:\n");
 while(row = mysql_fetch_row(res))
 {
   for (i = 0; i < columns; i++)
   {
     printf("%s ", row[i] ? row[i] : "NULL");
   }
   printf("\n");
 }

The mysql_num_fields() API returns the column number of the returned tables. The outer while loop iterated through the rows and the inner
for loop prints all columns of a row.

And finally the res if freed using mysql_free_result().

Compiling MySQL Client Code

Compiling the MySQL client code is tricky. First of all you need to have GCC installed on your system. You have to set proper compilation flag and libraries to link. To do that, we’ll use mysql_config utility to get compiler options. “mysql_config –cflags” returns C Compiler flags to find include files and critical compiler flags and defines used when compiling the libmysqlclient library. And “mysql_config –libs” Libraries and options required to link with the MySQL client library.
If your code is saved in test.c C file, then use this command to compile the code.

gcc -o mysqlc $(mysql_config --cflags) $(mysql_config --libs) test.c

The output binary will be stored as mysqlc.

If we run the program, the output will look like this.

./mysqlc
MySQL Tables in mysql database:
my_table
1 Cristiano Ronaldo
2 Lionel Messi

The post How to Access MySQL Database from C Program? appeared first on QnA Plus.


How to Implement Singly Linked List in C?

$
0
0

What is singly linked list?

In computer science, linked list is a collection of data elements, also called nodes, which are connected or linked by means of pointers or references. Connected or linked means if you have access to an element, you can go to the next element. In Singly linked list the links are unidirectional. You can only traverse from the first element to the last element but not in other direction.

Linked List
The above diagram shows a pictorial view of a singly linked list. This linked list has four data elements or nodes. Each node has an integer value and a link. The link either links (points) to NULL (in case of last node) or to another node, also referred as next node. The link (pointer in C) to the first node is also called head. This head is used to access the  whole linked list in a computer program. As the above diagram is of a singly linked list, every node has only one link that links or points to the next element or NULL.  No node points to the previous node. That means if we have access to a particular node, we can access to the next nodes towards the end of the list but we can never access to previous nodes.

C data structure for singly linked list

struct node{
    int val;
    struct node * next;
};

struct node *head = NULL;

The above code snippet shows the minimum data structures required to implement a linked list in C program. C structure (struct) is the basic building block of linked list. The structure will have two parts, data part and link part. In the above example, we have a structure call node. It has two members, one integer (val) and one link (next). For the data part we can have any type of data structure including complex C structure but the link has to be a pointer of same data type of the structure. Here the type of the structure is struct node, so the link (next) is pointer of type struct node. This will help to point to the same type of node. As I mentioned earlier we need to have one pointer (head) to point the first element of the list. So we took the head variable of type struct node which will be used to access the whole list. As we don’t have any element or node to begin with, we assigned the head with NULL.

C Implementation of Linked List

#include <stdio.h>
#include <stdlib.h>

struct node{
    int val;
    struct node *next;
};

void print_list(struct node *head)
{
    printf("H->");

    while(head)
    {
        printf("%d->", head->val);
        head = head->next;
    }

    printf("|||\n");
}

void insert_front(struct node **head, int value)
{
    struct node * new_node = NULL;

    new_node = (struct node *)malloc(sizeof(struct node));

    if (new_node == NULL)
    {
        printf("Failed to insert element. Out of memory");
    }

    new_node->val = value;
    new_node->next = *head;

    *head = new_node;
}

void main()
{
    int count = 0, i, val;
    struct node * head = NULL;

    printf("Enter number of elements: ");
    scanf("%d", &count);

    for (i = 0; i < count; i++)
    {
        printf("Enter %dth element: ", i);
        scanf("%d", &val);
        insert_front(&head, val);
    }

    printf("Linked List: ");
    print_list(head);
}

This program implements a linked list by taking inputs from the user and prints the list after that. In this program we construct the list by inserting element in the from of an existing list. The insert_front() function does that. In fact we can insert the new element in various places in the existing list. The insert_front() function first allocates memory for the new element and then insert that at the from of the existing list.

The main function takes the size of the list to be created and then asks for the value of every nodes in a loop. In every iteration it calls the insert_front() function to construct the list. After the it calls print_list() function to print the constructed list.

The sample output of the program is like this.

Enter number of elements: 4
Enter 0th element: 41
Enter 1th element: 53
Enter 2th element: 56
Enter 3th element: 76

Linked List: H->76->56->53->41->|||

The post How to Implement Singly Linked List in C? appeared first on QnA Plus.

How to Remove Duplicate Entries from Linked List in C Programming?

$
0
0

Here we’ll see how to write C program to remove duplicate entries from linked list. Duplicate entry means nodes with same value appear multiple times in the list.

Remove Duplicate Entries from Linked List

Linked list in the diagram above contains duplicate entries, 43, 24 and 5 appeared twice. We’ll write a program to remove these duplicate elements such that they appear only once in the result linked list along with the non-duplicate elements. Another import thing, the order of the elements will remain intact in the result linked list. The result will look like the diagram below

Linked list after removing duplicate entry

C Program to Remove Duplicate Entries from Linked List

#include <stdio.h>
#include <stdlib.h>

struct node{
 int val;
 struct node *next;
};

void print_list(struct node *head)
{
 printf("H->");

 while(head)
 {
  printf("%d->", head->val);
  head = head->next;
 }

 printf("|||\n");
}

void insert_front(struct node **head, int value)
{
 struct node * new_node = NULL;

 new_node = (struct node *)malloc(sizeof(struct node));

 if (new_node == NULL)
 {
  printf("Failed to insert element. Out of memory");
 }

 new_node->val = value;
 new_node->next = *head;

 *head = new_node;
}

void delete_node(struct node **head, struct node *node)
{
 struct node *tmp = NULL;

 if (head == NULL || *head == NULL) return;

 if(*head == node)
 {
  /*Delete the head node*/
  *head = (*head)->next;
  free(node);
  return;
 }

 tmp = *head;

 while(tmp->next && tmp->next != node) tmp = tmp->next;

 if(tmp->next)
 {
  tmp->next = tmp->next->next;
  free(node);
 }
 else
 {
  printf("Node not found in the list.\n");
 }
}

void remove_duplicate(struct node *head)
{
 struct node *tmp = NULL;
 struct node *tmp1 = NULL;
 struct node *tmp2 = NULL;

 if (head == NULL) return;

 tmp = head;
 while(tmp)
 {
  tmp1 = tmp->next;

  while(tmp1)
  {
    tmp2 = tmp1;
    tmp1 = tmp1->next;

    if(tmp->val == tmp2->val) delete_node(&head, tmp2);
  }

  tmp = tmp->next;
 }
}

void main()
{
 int count = 0, i, val;
 struct node * head = NULL;

 printf("Enter number of elements: ");
 scanf("%d", &count);

 for (i = 0; i < count; i++)
 {
  printf("Enter %dth element: ", i);
  scanf("%d", &val);
  insert_front(&head, val);
 }

 printf("Initial List: ");
 print_list(head);

 remove_duplicate(head);

 printf("List after removing duplicate entries: ");
 print_list(head);
}

Output of the Program

If you run the program the output would look like

Enter number of elements: 8
Enter 1th element: 43
Enter 2th element: 24
Enter 4th element: 5
Enter 5th element: 5
Enter 6th element: 24
Enter 7th element: 65
Enter 8th element: 43
Enter 9th element: 6
Initial List: H->6->43->65->24->5->5->24->43->|||
List after removing duplicate entries: H->6->43->65->24->5->|||

Explanation of the Program

The program takes input from user to construct the linked list. The user needs to enter some duplicate entries to see the affect. The remove_duplicate() function is used to remove duplicate entries from the linked list passed as argument.

void remove_duplicate(struct node *head)
{
 struct node *tmp = NULL;
 struct node *tmp1 = NULL;
 struct node *tmp2 = NULL;

 if (head == NULL) return;

 tmp = head;
 while(tmp)
 {
  tmp1 = tmp->next;

  while(tmp1)
  {
    tmp2 = tmp1;
    tmp1 = tmp1->next;

    if(tmp->val == tmp2->val) delete_node(&head, tmp2);
  }

  tmp = tmp->next;
 }
}

Logic is simple. The outer loop takes a node in every iteration starting from the first node and compares its value will rest of the right nodes in the list. If the value of any other node matches with outer loop node, the inner loop deletes that node from the linked list. The delete_node() function is used to delete the node. When the outer loop reaches end of the linked list, the linked list becomes duplicate entry free. The time complexity of the remove_duplicate() function is O(n2).

Note: The code of this article is compiled with gcc compiler on CentOS 7 system.

The post How to Remove Duplicate Entries from Linked List in C Programming? appeared first on QnA Plus.

How to Parse and Print XML File in Tree Form using libxml2 in C Programming?

$
0
0

Here we’ll see how to write C program to print XML file on the screen. XML file is widely used to store and transport data over internet. Parsing and using the data from an XML file is basic programming requirement.

Format of XML file

Before jumping into the code, it is important to understand the basic format of an XML file. Here is an sample XML file.

<?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications
      with XML.</description>
   </book>
   <book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-12-16</publish_date>
      <description>A former architect battles corporate zombies,
      an evil sorceress, and her own childhood to become queen
      of the world.</description>
   </book>
   <book id="bk103">
      <author>Corets, Eva</author>
      <title>Maeve Ascendant</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-11-17</publish_date>
      <description>After the collapse of a nanotechnology
      society in England, the young survivors lay the
      foundation for a new society.</description>
   </book>
</catalog>

XML is a markup language like HTML but here the tags are not predefined set. Any name can be used as tag in case off XML format, that’s why it is called eXtensible Markup Language. Few important constructs we need to know about the XML file.
Tag: tag is the basic markup construct of the XML file which begins with < and ends with >. In the example XML file the example of tags are <catalog> and <book> etc. It could be of three types, 1) start tag such as <catalog>, 2) end tag such as </catalog> and 3) empty element tag such as <catalog />. Example of empty element tag is not available in the example XML file is not shown though.
Element: Element is logical document component which is the mail building block of an XML file. It generally starts with a start tag and ends with an end tag. It could be an empty element tag also. The characters between the start tag and end tag, if any, are call the content of the element. Element can contain markup including other elements which are call children. Our example file contains one big element catalog which has few book elements. We can imagine an XML a file as a hierarchical tree structure of elements.
Attribute: Attribute is also a markup construct which is basically a name-value pair. It exists inside a start tag or empty element tag. In our XML file id is an example of an attribute in <book id=”bk101″> start tag.

C Program to Parse and Print XML file

The C program below can read any XML file and print in a tree structure. We’ll use the above XML file as the input of the program. File name is hard coded in the program. One important think to note that standard C libraries does not include the functionality to parse XML file. For that I used libxml2. To install libxml2 development package on RedHat based Linux, use this command.

yum install libxml2-devel

For Debian based Linux, use this command.

apt-get install libxml2-dev

Here is the complete C program.

#include <stdio.h>
#include <libxml/parser.h>

/*gcc `xml2-config --cflags --libs` test.c*/

int is_leaf(xmlNode * node)
{
  xmlNode * child = node->children;
  while(child)
  {
    if(child->type == XML_ELEMENT_NODE) return 0;

    child = child->next;
  }

  return 1;
}

void print_xml(xmlNode * node, int indent_len)
{
    while(node)
    {
        if(node->type == XML_ELEMENT_NODE)
        {
          printf("%*c%s:%s\n", indent_len*2, '-', node->name, is_leaf(node)?xmlNodeGetContent(node):xmlGetProp(node, "id"));
        }
        print_xml(node->children, indent_len + 1);
        node = node->next;
    }
}

int main(){
  xmlDoc *doc = NULL;
  xmlNode *root_element = NULL;

  doc = xmlReadFile("dummy.xml", NULL, 0);

  if (doc == NULL) {
    printf("Could not parse the XML file");
  }

  root_element = xmlDocGetRootElement(doc);

  print_xml(root_element, 1);

  xmlFreeDoc(doc);

  xmlCleanupParser();
}

In the main() function above xmlReadFile() loads and parses the XML file (dummy.xml) and returns the document tree. We get the root element of the XML from the document tree using the xmlDocGetRootElement() libxml2 function.

The root node (element) of the XML tree is passed to the print_xml() function to print the whole XML content in hierarchical form. This function traverse all siblings of the input node (including the passed node). If a node is of type ELEMENT then it prints some information about the node. libxml2 keeps other type of nodes also as sibling of the ELEMENT type node. That’s why we are skipping all node except ELEMENT type node. Tag name is printed and if the node is a leaf node, then we print content of the node, otherwise, we print the value of “id” attribute. We are not printing the content of non-leaf nodes because libxml2 return content of all nested children as the content of the node. The the content will be lengthy and repeated. Apart from print the information of the node, we are also call the same function print_xml() recursively for the children of the current node. This way all nodes will be printed.

The above program can be compile by this command.

gcc `xml2-config --cflags --libs` test.c

Output of the Program

-catalog:(null)
   -book:bk101
     -author:Gambardella, Matthew
     -title:XML Developer's Guide
     -genre:Computer
     -price:44.95
     -publish_date:2000-10-01
     -description:An in-depth look at creating applications
      with XML.
   -book:bk102
     -author:Ralls, Kim
     -title:Midnight Rain
     -genre:Fantasy
     -price:5.95
     -publish_date:2000-12-16
     -description:A former architect battles corporate zombies,
      an evil sorceress, and her own childhood to become queen
      of the world.
   -book:bk103
     -author:Corets, Eva
     -title:Maeve Ascendant
     -genre:Fantasy
     -price:5.95
     -publish_date:2000-11-17
     -description:After the collapse of a nanotechnology
      society in England, the young survivors lay the
      foundation for a new society.

The post How to Parse and Print XML File in Tree Form using libxml2 in C Programming? appeared first on QnA Plus.

How to Implement Insertion Sort in C Programming?

$
0
0

Insertion sort is very popular sorting algorithm which is probably taught among first few sorting techniques in programming syllabus. Its popularity is not because of its performance but for its simplicity. Its performance is not as good as quick or shell short for large number of elements but it is very simple like bubble sort. It is often used for less number of elements especially when the input list or array is substantially sorted.  Here we’ll see how to implement insertion sort in C programming language. We’ll also discuss its performance in various conditions.

Insertion Sort Algorithm

In insertion sort, at any point of time, there will be two sub-arrays, one is sorted and other is not. One item (element) is taken from the unsorted sub-array and inserted in the sorted sub-array such that the sorted sub-array remains sorted. This process continues until the while array becomes sorted. At every stage the task is to take an element and insert that to an appropriate place, that’s why the name is insertion sort.

Insertion sort is often compared the way we sort cards in our hand in the game of cards. We keep our cards sorted in our hand in time of dealing. When we get a new card from the dealer, our job is to insert the card at right place such the cards in our hand remain sorted. To do that we compare the new card with the right most card in our hand. If the new card is greater than the right most card, then we place the card next to right most card, otherwise, we compare the card with the second right most card. If the new card is greater than the second right most card then place it next to the second right most card, otherwise, continue the process until the new card gets a right place. If the new card is smaller than any card in hand then it will get the left most position. Same thing we do with our array in case of insertion sort.

Graphical Illustration of Insertion Sort

Graphical Illustration of Insertion Sort in C
The diagram shows how insertion sort works. At step 1, the array is sub-divided into two parts. First element is one part and rest of the elements come in the second part. First sub-array will be always sorted. At step 1, as there is only one element in the left sub-array, it is sorted by default. Then take the first element of the right sub-array and find a right place in the left sub-array to insert the element such that the left sub-array remains sorted. In this case 4 will come before 6. Similar process continues until all elements from right sub-array come to the left sorted sub-array.

Implementation of Insertion Sort in C

Here is the implementation of insertion sort in C programming.

#include <stdio.h>

void insertion_sort(int *arr, int n)
{
  int i = 0, j = 0, tmp = 0;

  for (i = 1; i < n; i++)
  {
      tmp = arr[i];
      j = i - 1;
      while(j >= 0 && tmp < arr[j])
      {
        arr[j+1] = arr[j];
        j--;
      }
      arr[j+1] = tmp;
  }
}

void main()
{
  int arr[] = {54, 66, 31, 10, 4, 77, 32, 1, 56};
  int i = 0;

  printf("Array before sorting: ");
  for (i = 0; i < (sizeof(arr)/sizeof(int)); i++) printf(" %d", arr[i]);
  printf("\n");

  insertion_sort(arr, sizeof(arr)/sizeof(int));
  printf("Array after sorting: ");
  for (i = 0; i < (sizeof(arr)/sizeof(int)); i++) printf(" %d", arr[i]);
  printf("\n");
}

The insertion_sorted() function takes an array as input and applies insertion sort algorithm to sort that array. The outer loop iterates n-1 times where n is the number of elements in the array. The inner loop finds the appropriate position for i-th element in first i elements in the array which are already sorted. As soon as it find the right place (j+1) it terminates. The i-th element is place in the right place (j+1 th position) outside the inner loop.

Output of the program:

Array before sorting:  54 66 31 10 4 77 32 1 56
Array after sorting:  1 4 10 31 32 54 56 66 77

Performance of Insertion Sort

Worst case: Worst case running time of insertion sort in Big-O notation is O(N2). Worst case scenario occurs when the array is in reverse order we are sorting for. For example, if we want to sort an array in ascending order and the array is in the descending order to begin with. In this case we’ll have maximum number of comparisons.

Insertion Sort Worst Case Performance

The above diagram shows how insertion sort performs in worst case condition. It shows how number of comparisons increases with the number of input elements. In this case running time is directly proportional to number of comparisons. If you look into the graph or table carefully, you’ll notice that if the number of input elements doubles the number of comparisons is increased by four times. If the number of input elements increases by four times, then number of comparisons is increased by sixteen times. That’s why the running time is O(N2).

Average case: Average case running time of insertion sort in Big-O notation is O(n2). Average case occurs for an array where the elements are in random order at the beginning.

Insertion Sort Average Case Performance

The  above diagram shows the performance of insertion sort in average case. Here the actual number of comparisons is less compare than that of the worst case. But the growth rate is same as the worst case. Here also If the number of input elements are doubled, the number of comparisons will be increased by four times. Similarly if the number of elements increases by four times, the number of comparisons increases sixteen times.

Best case: Best case running time of insertion sort in Big-O notation is O(N). Best case scenario occurs if the array is already sorted. In that case the inner loop will terminate immediately after first comparison.

Insertion Sort Best Case Performance

In best case the number of comparison required is linear with respect to the number of inputs. That means if we double the number of inputs, the number of comparisons required will also be double.

The diagram below compares three conditions (worst, average and best cases)

Insertion Sort Performance
Running time in best case is negligible compare to worst or best cases for large number of input elements. The time requirement for average case is always less than worst case but their growth rate is same.

The post How to Implement Insertion Sort in C Programming? appeared first on QnA Plus.

How to Implement Bubble Sort in C Program?

$
0
0

Here we’ll see how to implement bubble sort in C programming language. Bubble sort probably is among the first few sorting algorithms that are being taught in programming syllabus. Its popularity is not because of its performance but because of its simplicity. In fact bubble sort is not suitable in most of the practical cases because of its inefficiency in terms of running time requirement. But it very easy to understand and code compare to other sorting algorithms like quick sort or merge sort.

Bubble Sort Algorithm

Bubble sort algorithm is quite simple, continuously swap two adjacent elements if they are not in the right order until no swapping is required.

In bubble sort two nested loops are required. Inner loop starts from the first position and checks the elements of current position and next position whether they are in right order. If they are not then it swaps them. Then move to the next position. After every iteration of the outer loop one element will be place in the right position. For example we want to sort an array in ascending our, the biggest element will come to the last position after end of the first iteration. Similarly after end of the second iteration, the second biggest element will come to the second last positions. In this way after n-1 iterations, n-1 elements will take the right position and the remaining last element will be in the right position.

Graphical Illustration of Bubble Sort

Graphical Illustration of Bubble Sort
The above diagram shows how the highest element reaches to the last position in the array after first iteration of bubble sort. Similarly in the second iteration the second biggest element will take the second last position. If we continue this process for n-1 time then all n elements will take the right positions in the final sorted array.

Implementation of bubble sort in C

Here we’ll discuss about various implementation options of bubble sort in C programming language and their differences.

Variation 1:

We’ll start with the simplest implementation of bubble sort.

void bubble_sort(int *arr, int n)
{
  int i = 0, j = 0;
  int tmp = 0;

  for(i = 0; i < n-1; i++)
  {
    for (j = 0; j < n-1; j++)
    {
      if(arr[j+1] < arr[j])
      {
         tmp = arr[j];
         arr[j] = arr[j+1];
         arr[j+1] = tmp;
      }
    }
  }
}

This is very easy to remember variation. In this case, the outer loop and inner loop both iterate n-1 times where n is not number of elements in the array. The inner loop starts from the first element and checks with the next element whether they are in correct order. If not then swaps the elements. In this example we are sorting the array in ascending order. So if the current element (indexed by j) is greater than the next element (indexed by j+1), then swap them. After doing this the control moves to the next element. In this case, we’ll have (n-1)*(n-1) comparisons always which is more the the maximum comparison required by bubble sort even in the worst case. In the following sections, we’ll see how we can improve the implementation to minimize number of comparisons.

Variation 2:

As we discussed earlier, in every iteration of the outer loop, one element of the array is place in the right location. We can use this property to improve our implementation. For every iteration of the outer loop, we’ll iterate the inner loop one less time.

void bubble_sort(int *arr, int n)
{
  int i = 0, j = 0;
  int tmp = 0;

  for(i = 0; i < n-1; i++)
  {
    for (j = 0; j < n-i-1; j++)
    {
      if(arr[j+1] < arr[j])
      {
         tmp = arr[j];
         arr[j] = arr[j+1];
         arr[j+1] = tmp;
      }
    }
  }
}

This done by changing the inner loop. We changed the loop from:

for (j = 0; j < n-1; j++)

to:

for (j = 0; j < n-i-1; j++)

As the value of i increases, the inner loop will iterate less.

Variation 3:

Our implementation can further be improved by terminating the outer loop if inner loop does not do swapping. If the inner loop does not do swapping, that means the array is already sorted and we don’t need to run the outer loop.

void bubble_sort(int *arr, int n)
{
int i = 0;
  int tmp = 0;
  int swapped = 0;
  do
  {
    swapped = 0;
    for (i = 0; i < n-1; i++)
    {
      if(arr[i+1] < arr[i])
      {
         tmp = arr[i];
         arr[i] = arr[i+1];
         arr[i+1] = tmp;
         swapped = 1;
      }
    }
    n = n - 1;
  } while (swapped == 1);
}

We changed the outer loop to do-while but could continue with for loop also. In this situation do-while loop is more appropriate the for loop. As we don’t have the outer for loop here, therefore, we don’t have the i variable. To reduce the inner loop iterations, we added the instruction n = n-1 after the end of the inner loop. The inner loop checks whether it does swapping. If it does, then the outer loop continues, otherwise terminates.

Variation 4:

Our implementation can further be improved. In our previous implementations, we were reducing the inner loop iterations by one for every outer loop iteration. But we can remember where (at which index) we did the last swapping in the inner loop. The rest of the array is already sorted. In the next iteration of the outer loop, we can stop the inner loop where it did swapping in the last iteration.

void bubble_sort(int *arr, int n)
{
  int i = 0;
  int tmp = 0;
  int newn = 0;
  int swapped = 0;
  do
  {
    swapped = 0;
    for (i = 0; i < n-1; i++)
    {
      if(arr[i+1] < arr[i])
      {
         tmp = arr[i];
         arr[i] = arr[i+1];
         arr[i+1] = tmp;
         swapped = 1;
         newn = i + 1;
      }
    }
    n = newn;
  } while (swapped == 1);
}

In this implementation, the newn remembers where the inner loop did swapping. Next time the inner loop will go up to newn. This is the most optimized implementation of bubble sort as per the number of comparisons is concerned.

Performance of bubble sort

Worst Case:

Worst case running time of bubble sort in Big-O notation is O(N2). Worst case scenario occurs when the array is in the opposite order that we are doing sorting for. For example, if we have to sort an array in ascending order the array is in descending order at the beginning.

Bubble Sort worst case performance analysis

The above diagram show how our 4 implementations perform in worst case scenarios. Here we’ll see how the number of comparisons increases with the increase of number of input elements. Number of comparisons is directly proportional to the running time requirement. From the graph we can see the the first variation takes maximum number of comparison. Other 3 variation take equal number of comparisons but less than the first variation. We should notice one important thing here that growth rate of all four variations is same. If we double the number of inputs then the number of comparisons will become four times. If we increase the number of elements by four times then the number of comparisons will increase by sixteen times. That means the growth rate is O(N2) in Big-O notation

Average Case:

Average case running time of bubble sort in Big-O notation is also O(N2). Average case means at the beginning the array is in random order.

Bubble Sort average case performance analysis

The above diagram shows the performance of our bubble sort implementation is average case. We can see the the first variation takes maximum number of comparisons, then the second one, then third and the fourth variation takes least number of comparison. But here also the growth rate of running time or required comparison is same, i.e. O(N2). If we double the number of inputs, the number of comparisons becomes four times.

Best Case:

Best case running time of bubble sort in Big-O notation is O(N). Best case scenario occurs when the array is already sorted at the beginning.

Bubble Sort best case performance analysis

Here we can see that the growth rate of first two variations of our implementations is O(N2). Second variation is slightly better than the first one in terms of actual number of comparisons. But our last two variations perform performs much better than the first two. The growth rate of third and fourth variations is linear. They always take n-1 number of comparisons.

The post How to Implement Bubble Sort in C Program? appeared first on QnA Plus.

Viewing all 93 articles
Browse latest View live