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

Custom Deleter in std::unique_ptr

$
0
0

In the previous article, we saw how std::unique_ptr helps to clean memory. Generally it calls the default deleter (C++ delete operator) in appropriate time to clean up the allocated memory. But many times default deleter is not good enough for the pointer that you are dealing with. For example, if you work with file pointer (std::FILE *), cleaning up memory does not mean to delete the pointer. You have to close the opened file. Forgetting to close a file is a very common programming mistake in C++. Default deleter can not close a file. Here you have to use your own custom deleter that will perform your custom operation like closing the file.

How to Provide Custom Deleter to std::pointer?

The std::unique_ptr constructor takes two arguments, 1) the pointer that it owns and manages, 2) optionally a deleter which is a function pointer or std::func object. If you don’t specify the second argument, it will use C++ delete operator as default deleter. You can specify your own function as deleter.

// File Name: test.cpp
// To compile: g++ test.cpp -std=c++11
#include <iostream>
#include <fstream>
#include <memory>

void close_file(std::FILE* fp) {
  std::cout << "Closing file..." << std::endl;
  std::fclose(fp);
}

int main() {
  std::ofstream("myfile.txt") << "qnaplus.com";
  std::unique_ptr<std::FILE, decltype(&close_file)> fp(std::fopen("myfile.txt", "r"), &close_file);

  char str[16];
  if(fp) {
    std::cout << std::fgets(str, 16, fp.get()) << std::endl;
  }
  return 0;
}

Here, in time of creating the std::unique_ptr we provided a file pointer, fp, and our custom deleter function close_file(). When the std::unique_ptr will go out of context, the close_file() function will get called that will close the file. As we specified a custom deleter, default delete would not get called.

Lamda Function as Deleter

We can use a lamda function as deleter also. The same solution can be written as follows. This program and the above are basically same.

#include <iostream>
#include <fstream>
#include <memory>

int main() {
  std::ofstream("myfile.txt") << "qnaplus.com";
  std::unique_ptr<std::FILE, std::function<void(std::FILE *)>> fp(std::fopen("myfile.txt", "r"),
                                                           [](std::FILE *f){
                                                               std::cout << "Closing file..." << std::endl;
                                                               std::fclose(f);
                                                           });

  char str[16];
  if(fp) {
    std::cout << std::fgets(str, 16, fp.get()) << std::endl;
  }
  return 0;
}

The post Custom Deleter in std::unique_ptr appeared first on QnA Plus.


Move std::unique_ptr to Pass to a Function or Assign to Another Variable

$
0
0

The std::unique_ptr has unique ownership of the object it manages. That means only one std::unique_ptr can contain the actual object pointer. That’s why we can not assign a std::unique_ptr to another one. For the same reason we can not pass std::unique_ptr as an argument of a function. But we can move the ownership of the object to a new std::unique_ptr. After moving the ownership new variable (assigned one) will own the object. We’ll no longer be able to access the object from the old std::unique_ptr.

We’ll use this class in our examples in this article.

class C {
public:
  C() {
    std::cout << "Constructing the class..." << std::endl;
  }

  ~C() {
    std::cout << "Destructing the class..." << std::endl;
  }

  void f() {
    std::cout << "Printing from function f()..." << std::endl;
  }
};

We can create a std::unique_ptr of C type object like this.

std::unique_ptr<C> pc = std::unique_ptr<C>(new C());

But we can not assign this std::unique_ptr, pc, to another one.

std::unique_ptr<C> new_pc = pc;

This will produce compilation errors. But we can move the ownership of the actual pointer to new std::unique_ptr.

std::unique_ptr<C> new_pc = std::move(pc);

After this, pc will no longer own the actual pointer. We won’t be able to use the old unique_ptr, pc.

if(pc == nullptr) {
  std::cout << "pc does not own the actual pointer" << std::endl;
}

The “pc == nullptr” checking will return true. But we’ll be able to use the new std::unique_ptr, new_pc. We can call the new_pc->f() function.

Passing std::unique_ptr to Function

Similar thing happens when we try to pass a std::unique_ptr a function as parameter. Here is a function that takes std::unique_ptr as input.

std::unique_ptr<C> func1(std::unique_ptr<C> ptr)
{
  ptr->f();
  return ptr;
}

If we try to call this function like this:

std::unique_ptr<C> pc = std::unique_ptr<C>(new C());
func1(pc)

It will produce compilation errors. We have to move the ownership of the actual pointer like this.

std::unique_ptr ret = func1(std::move(pc));

After this statement, pc will no longer own the actual pointer.

But when a function returns a std::unique_ptr, the ownership is automatically transferred to the returned variable. In this example, after func1 returns, ret will own the actual pointer. We’ll be able to call ret->f() function.

The post Move std::unique_ptr to Pass to a Function or Assign to Another Variable appeared first on QnA Plus.

C Program to Merge Two Sorted Arrays into one Sorted Array

$
0
0

Here we’ll write a C function to merge two sorted arrays into one. The merged array will also be sorted. Here we’ll use two sorted integer arrays that are sorted in ascending order. After merging the result array will contain all the numbers from the original arrays and will be sorted in ascending order. The logic will be similar for descending arrays.

We use this technique in conquer phase of merge sort.

int merge(int *arr1, int len1, int *arr2, int len2, int *arr) {
    int i = 0, j = 0, k = 0;
    while((j < len1) && (k < len2)) {
        arr[i++] = (arr1[j] < arr2[k])?arr1[j++]:arr2[k++];
    }

    while(j < len1) arr[i++] = arr1[j++];
    while(k < len2) arr[i++] = arr2[k++];
    
    return i;
}

Input parameters of this function:
arr1: First sorted array
len1: Length of the first array.
arr2: Second sorted array.
len2: Length of the second array.
arr: Output result array.

This function returns the length of the merged array which basically len1 plus len2.

We maintain three index variables i, j and k for three arrays, two input arrays (arr1 and arr2) and the output array (arr). The first while loop continues until all elements of one of the input arrays are copied into the result array (arr). In every iteration, if arr1[j] is smaller than arr2[k], then arr1[j] is copied to arr[i] and i and j are incremented by 1. Similarly, if arr2[k] is smaller than arr1[j] then arr2[k] is copied to arr[i] and i and j are incremented by 1.

After completion of the first while loop all numbers from one of the two arrays are copied to the result array. The next two while loops copy the remaining numbers of the other array to the result array.

The Complete Program.

Here is the complete program.

#include <stdio.h>

int merge(int *arr1, int len1, int *arr2, int len2, int *arr) {
    int i = 0, j = 0, k = 0;
    while((j < len1) && (k < len2)) {
        arr[i++] = (arr1[j] < arr2[k])?arr1[j++]:arr2[k++];
    }

    while(j < len1) arr[i++] = arr1[j++];
    while(k < len2) arr[i++] = arr2[k++];
    
    return i;
}

void print_arr(int *arr, int len) {
    int i = 0;
    while(i < len) {
        printf("%d ", arr[i++]);
    }
    printf("\n");
}

int main() {
    int arr1[] = {3, 5, 7, 10, 15, 19, 21, 34, 67};
    int arr2[] = {1, 4, 7, 9, 18, 26, 30, 56, 71, 81, 94};
    int arr[32] = {0};
    int len = 0;
    int l1 = sizeof(arr1) / sizeof(int);
    int l2 = sizeof(arr2) / sizeof(int);
    
    printf("First Array: ");
    print_arr(arr1, l1);
    printf("Second Array: ");
    print_arr(arr2, l2);

    len = merge(arr1, l1, arr2, l2, arr);
    printf("Merged Array: ");
    print_arr(arr, len);
    return 0;
}

Here is the output of the program.

First Array: 3 5 7 10 15 19 21 34 67
Second Array: 1 4 7 9 18 26 30 56 71 81 94
Merged Array: 1 3 4 5 7 7 9 10 15 18 19 21 26 30 34 56 67 71 81 94

The post C Program to Merge Two Sorted Arrays into one Sorted Array appeared first on QnA Plus.

C Program to Find Minimum and Maximum Numbers in an Array

$
0
0

Here we’ll see how to write C program to find the minimum and maximum numbers in an array.

#include <stdio.h>

int main()
{
    int arr[128];
    int n = 0, i = 0, min = 0, max = 0;
    
    printf("Enter the number of elements of the array: ");
    scanf("%d", &n);
    
    for(i = 0; i < n; i++) {
        printf("arr[%d] = ", i);
        scanf("%d", &arr[i]);
    }
    
    min = arr[0];
    max = arr[0];
    
    for(i = 1; i < n; i++) {
        if(arr[i] < min) {
            min = arr[i];
        } else if (arr[i] > max) {
            max = arr[i];
        }
    }
    
    printf("Minimum number in the array: %d.\n", min);
    printf("Maximum number in the array: %d.\n", max);
    return 0;
}

Here we assigned the first element of the array to both minimum (min) and maximum (max). Then we traverse the array from the second element to the last element. If any element is smaller than the current min value, then that element is assigned to min. Similarly, if an element is greater than the current max, then that element is assigned to max.

Here is the output of the program.

Minimum and maximum of a array.

The post C Program to Find Minimum and Maximum Numbers in an Array appeared first on QnA Plus.

C Program to Calculate Factorial of a Number

$
0
0

Factorial of a number N, (N!) is 1*2*3*4*5*…..*N. Here we’ll see how to write C program to calculate the factorial value of a number.

Here are the C functions that calculate the factorial value of a the input number.

Using FOR Loop

unsigned long factorial(int n) {
    unsigned long f = 1;
    int i;
    
    for(i = 1; i <= n; i++) {
        f *= i;
    }
    
    return f;
}

Using WHILE Loop

unsigned long factorial(int n) {
    unsigned long f = 1;
    
    while(n) f *= n--;
    
    return f;
}

Using Recursion

unsigned long factorial(int n) {
    if(n == 0) return 1;
    
    return factorial(n-1) * n;
}

Complete Program

Any one of the above functions can be used in the program.

#include <stdio.h>

unsigned long factorial(int n) {
    unsigned long f = 1;
    
    while(n) f *= n--;
    
    return f;
}

int main()
{
    int n;
    unsigned long f = 0;
    
    printf("Enter a number: ");
    scanf("%d", &n);
    
    if(n < 0) {
        printf("Factorial not possible for a negative number.\n");
        return 0;
    }
    
    f = factorial(n);
    printf("Factorial of %d is %lu", n, f);
    
    return 0;
}

Here is the output of the program.

factorial of a number

The post C Program to Calculate Factorial of a Number appeared first on QnA Plus.

Change a Variable from inside a C Function

$
0
0

Here we’ll see how we can change a variable from inside a C function. Let’s consider the following code snippet.

#include <stdio.h>

void change_value(int v) {

  printf("Value of input variable in function change_value(): %d.\n", v);
  v = v + 100;
  printf("Value of input variable in function change_value() is changed to: %d.\n", v);
}

int main(){
  int x = 5;
  
  change_value(x);
  printf("Value of x after calling change_value(): %d.\n", x);
}

Here in main(), we have a variable x with value 5. We tried to change the value of x in function change_value() by adding 100 with it.

Here is the output of this program.

Value of input variable in function change_value(): 5.
Value of input variable in function change_value() is changed to: 105.
Value of x after calling change_value(): 5.

From this output it is clear that even though the variable is changed to 105 inside the function, the value of x remains 5 after coming out of the function. When we printed x in main() after the function call, it prints 5.

Here are a few ways we can change a variable from inside a function.

Using Global Variable

We can make the variable x global. Here is the program.

#include <stdio.h>

int x = 0;

void change_value() {

  printf("Value of input variable in function change_value(): %d.\n", x);
  x = x + 100;
  printf("Value of input variable in function change_value() is changed to: %d.\n", x);
}

int main(){
  x = 5;
  
  change_value();
  printf("Value of x after calling change_value(): %d.\n", x);
}

As variable x is now global, we don’t need to pass that as function parameter.

Output:

Value of input variable in function change_value(): 5.
Value of input variable in function change_value() is changed to: 105.
Value of x after calling change_value(): 105.

From this output we can see the changed value even after the function call. If you change a global variable from any function, you’ll be able to see the changed value in any other functions.

Main problem with this approach is that we have to use global variable. In general global variable usage is not recommended unless absolutely required. Managing too many global variables is difficult.

Returning the Changed Value

Instead of using a global variable, we can return the changed value from the function. Here is the example code.

int change_value(int v) {

  printf("Value of input variable in function change_value(): %d.\n", v);
  v = v + 100;
  printf("Value of input variable in function change_value() is changed to: %d.\n", v);
  return v;
}

int main(){
  int x = 5;
  
  x = change_value(x);
  printf("Value of x after calling change_value(): %d.\n", x);
}

Output:

Value of input variable in function change_value(): 5.
Value of input variable in function change_value() is changed to: 105.
Value of x after calling change_value(): 105.

Here the function returned the changed value. Problem with this approach is that if you want to change multiple variables in a single function call, you can not do that. Because C function can return only one variable at a time. There are tricks to return multiple values using struct but things are complicated.

Using Call by Reference

This probably is the most elegant solution. Instead of passing the value of the variable, we can pass the reference or pointer of the variable as input parameter of the function. Using that pointer we’d be able to change the variable. This mechanism is also know as ‘Call by Reference’. Here is the code.

#include <stdio.h>

void change_value(int* v) {

  printf("Value of input variable in function change_value(): %d.\n", *v);
  *v = *v + 100;
  printf("Value of input variable in function change_value() is changed to: %d.\n", *v);
}

int main(){
  int x = 5;
  
  change_value(&x);
  printf("Value of x after calling change_value(): %d.\n", x);
}

And here is the expected output.

Value of input variable in function change_value(): 5.
Value of input variable in function change_value() is changed to: 105.
Value of x after calling change_value(): 105.

The post Change a Variable from inside a C Function appeared first on QnA Plus.

Change a Pointer from inside a C Function

$
0
0

We can change normal variable from inside a C function by passing the pointer of the variable. Here we’ll see how to change a pointer variable from inside a C function.

Concept is same, here we have to pass the pointer of the pointer to the function.

Code Snippet

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

void change_pointer(int** p) {

  *p = (int*)malloc(sizeof(int));
  **p = 10;
}

int main(){
  int x = 5;
  int *p = &x;
  printf("Before function call: pointer %p is pointing to %d.\n", p, *p);
  
  change_pointer(&p);
  printf("After function call: pointer %p is pointing to %d.\n", p, *p);
}

Here is the output.

Before function call: pointer 0x7ffd5234 is pointing to 5.
After function call: pointer 0x1b721605 is pointing to 10.

In main(), we have an integer pointer, p. We assigned p with the reference (or pointer) of variable x (&x).

From the first output, we can see the value of the pointer p (0x7ffd5234), and the value (5) the pointer is pointing to.

Now we want to change the pointer itself. So we passed the pointer of p (&p) to the change_pointer() function.

In the change_pointer() function, we allocated a new integer pointer and assigned that to *p. We assigned a new value (10) to the newly allocated pointer. Note that we did not assign a pointer of location variable to *p. Because the local variable will become invalidate after the change_pointer() function will return.

After the function return we can see from the second output that the pointer is changed from 0x7ffd5234 to 0x1b721605. The new pointer is pointing to a new value 10.

The post Change a Pointer from inside a C Function appeared first on QnA Plus.

C Program to Check a Bit of an Integer

$
0
0

An integer consists of 32 bits. Here we’ll see how to write C program to check whether a particular bit is 0 or 1.

The above diagram shows the binary representation of an integer 8,55,119. Bit position will start from 0. That means the least significant bit position is 0 and the most significant bit position is 31. So the 10-th bit of the above integer is 1.

Program to Check a Bit

#include <stdio.h>

int check_bit(int val, int n) {
  return ((val >> n) & 0x01);
}

int main(){
  int x = 0;
  int pos = 0;

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

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

  printf("%d-th position of %d is %d.\n", pos, x, check_bit(x, pos));
}

The check_bit() function returns the n-th bit of val. If n-th bit is 1, the function returns 1. Similarly if n-th bit is 0, the function returns 0.

The check_bit() function first brings the n-th bit to the 0-th position by shifting n bits (val >> n). If we do bitwise AND (&) operation with the shifted number, the result will be equal to the 0-th bit position.

Here is the output of the program.

Enter an integer: 855119
Enter position: 10
10-th position of 855119 is 1.

Enter an integer: 855119
Enter position: 9
9-th position of 855119 is 0.

The post C Program to Check a Bit of an Integer appeared first on QnA Plus.


C Program to Copy an Array to Another

$
0
0

We can not copy an array using simple assignment operation like any other primitive data types. Here we’ll discuss the techniques to copy an array from one to another.

By Traversing

We can copy an array by traversing the source array – coping one element in each iteration. This is simplest, most common and widely used mechanism.

/*test.c*/

#include <stdio.h>

void print_array(int* arr, int size) {
  int i = 0;
  for (i = 0; i < size; i++) {
    printf("%d ", arr[i]);
  }
  printf("\n");
}

int main(){
  const int MAX_SIZE = 32;
  int size = 0;
  int arr_src[MAX_SIZE];
  int arr_dst[MAX_SIZE];
  int i = 0;

  printf("Enter size: ");
  scanf("%d", &size);

  printf("Enter the array elements:\n");
  for(i = 0; i < size; i++) {
    printf("arr[%d] = ", i);
    scanf("%d", arr_src + i);
  }

  printf("\nThe entered array:\n");
  print_array(arr_src, size);

  /* Copying the array */
  for(i = 0; i < size; i++) {
    arr_dst[i] = arr_src[i];
  }

  printf("The copied array:\n");
  print_array(arr_dst, size);
}

Here we first take input of the source array. Then we traversed the array and in every iteration we copied one element from source array to the destination. Array elements are referred by index i. We printed the input array before copying. After copying that to the destination array, we printed the destination array.

Here is the output.

Using Memory Copy

Array elements are stored in consecutive memory locations. Instead of traversing the array, we can copy the whole array in one memory copy operation.

/*test.c*/

#include <stdio.h>
#include <memory.h>

void print_array(int* arr, int size) {
  int i = 0;
  for (i = 0; i < size; i++) {
    printf("%d ", arr[i]);
  }
  printf("\n");
}

int main(){
  const int MAX_SIZE = 32;
  int size = 0;
  int arr_src[MAX_SIZE];
  int arr_dst[MAX_SIZE];
  int total_size = 0;
  int i = 0;

  printf("Enter size: ");
  scanf("%d", &size);

  printf("Enter the array elements:\n");
  for(i = 0; i < size; i++) {
    printf("arr[%d] = ", i);
    scanf("%d", arr_src + i);
  }

  printf("\nThe entered array:\n");
  print_array(arr_src, size);

  /* Copying the array */
  total_size = size * sizeof(int);
  memcpy(arr_dst, arr_src, total_size);

  printf("The copied array:\n");
  print_array(arr_dst, size);
}

Here first we calculated the total size (total_size) of the array. The array has size elements. Each element is an integer. So the total size is size * sizeof(int).

In the next statement we copied the whole array of size total_size using memcpy.

Output of this program would be exactly same as the first program.

The post C Program to Copy an Array to Another appeared first on QnA Plus.

Count Occurrences of a Substring in a String in C

$
0
0

Here we’ll see how to write C program to find out the number of occurrences of a substring in a string. C string library (<string.h>) provides a function (strstr()) to determine whether a sub-string is present in a string or not. But that does not count the number of occurrences. We can implement our own function for that with or without using strstr() function.

The Program

/*test.c*/

#include <stdio.h>
#include <string.h>

#define MAX_STRING_SIZE 1024

int substring_count(char* string, char* substring) {
  int i, j, l1, l2;
  int count = 0;
  int found = 0;

  l1 = strlen(string);
  l2 = strlen(substring);

  for(i = 0; i < l1 - l2; i++) {
    found = 1;
    for(j = 0; j < l2; j++) {
      if(string[i+j] != substring[j]) {
        found = 0;
        break;
      }
    }

    if(found) {
      count++;
      i = i + l2 -1;
    }
  }

  return count;
}

int main(){
  char string[MAX_STRING_SIZE];
  char substring[MAX_STRING_SIZE];
  int count = 0;

  printf("Enter a string: ");
  gets(string);

  printf("Enter a substring: ");
  gets(substring);

  count = substring_count(string, substring);

  printf("Substring occurrence count is: %d.\n", count);

  return 0;
}

This program takes two inputs, the string and the sub-string. The substring_count() function counts the number of occurrence of the sub-string. It iterates the string character by character and assumes that every character could be the beginning of the sub-string. It starts matching with the sub-string characters from there. If any mismatch is found (line 19), the inner loop breaks and the outer loop advances to the next character to repeat the same thing. If the all characters match in the inner loop, then match counter is incremented (line 26). The outer loop advanced by the length of the sub-string.

Here is the output.

Using strstr() Function

The substring_count() function is changed like this.

int substring_count(char* string, char* substring) {
  int i, j, l1, l2;
  int count = 0;

  l1 = strlen(string);
  l2 = strlen(substring);

  for(i = 0; i < l1 - l2; i++) {
    if(strstr(string + i, substring) == string + i) {
      count++;
      i = i + l2 -1;
    }
  }

  return count;
}

Instead of having our own inner loop to check whether the sub-string matches from a particular of the outer loop, we used the strstr() function. Function strstr() returns the pointer of starting character of the first match. If the pointer is equal to the pointer of starting character of the outer loop, we increment match counter.

We can achieve the same thing using strcmp() function also.

The post Count Occurrences of a Substring in a String in C appeared first on QnA Plus.

C Program to Count Characters, Words and Lines in a File

$
0
0

To get a quick summary like total number of characters, words and limes in a file, Linux already has a tool, wc. Here we’ll see how to write C program to get the similar information.

Strategy to Count Characters, Words, Lines in a File

  1. Take input of a file name and open that file in a read only mode. Don’t continue if the file can’t be opened.
  2. Traverse the file character by character until you get the EOF character. Every file ends with the EOF character.
    1. Increment the character count.
    2. If the character is not a white-space character, set a flag in_word to 1.
    3. If the character is a white-space and the in_word flag is 1, increment the word count and set the in_word flag to 0.
      1. If the character is either ‘\n’ or ‘\0’, increment the line count.

The Program

/*test.c*/

#include <stdio.h>
#define MAX_LEN 1024

int main() {
  /*Read the file.*/

  char ch;
  int char_count = 0, word_count = 0, line_count = 0;
  int in_word = 0;
  char file_name[MAX_LEN];
  FILE *fp;

  printf("Enter a file name: ");
  scanf("%s", file_name);

  fp = fopen(file_name, "r");

  if(fp == NULL) {
    printf("Could not open the file %s\n", file_name);
    return 1;
  }

  while ((ch = fgetc(fp)) != EOF) {
    char_count++;

    if(ch == ' ' || ch == '\t' || ch == '\0' || ch == '\n') {
      if (in_word) {
        in_word = 0;
        word_count++;
      }

      if(ch = '\0' || ch == '\n') line_count++;

    } else {
      in_word = 1;
    }
  }

  printf("In the file %s:\n", file_name);
  printf("Number of characters: %d.\n", char_count);
  printf("Number of words: %d.\n", word_count);
  printf("Number of lines: %d.\n", line_count);

  return 0;
}

Here is the content of out sample text file (test.txt).

Electric communication will never
be a substitute for the face of
someone who with their soul encourages
another person to be brave and true

And here is the output of the program.

character, word and line count in a file

Here character count includes all characters including white spaces. Word is consecutive non-white-space characters. And line ends with ‘\0’ or ‘\n’ character.

The post C Program to Count Characters, Words and Lines in a File appeared first on QnA Plus.

C Program to Reverse a Linked List

$
0
0

Reversing a linked list means re-arranging the next (connection) pointers. Head will point to the last node and the first node will point to NULL. Direction of other next pointers will change.

If a linked list looks like this:

Linked List

After reversal, it will look like:

Linked List Reversed

Logic to Reverse a Linked List

  1. Take the first node out of the linked list. One new pointer will point to the first node and the head will move to the next node.
  2. Insert the node at the from of the new list.
  3. Repeat previous two steps until all nodes move to the new list.
  4. Pointer the head of the original linked list to the first node of the new list.

Reverse Linked List Program

/*
 * File name: test.c
 * Compile: cc test.c
 * */
#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\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 reverse_linked_list(struct node **head) {
  struct node *new_head = NULL; /*head of the reversed list*/
  struct node *tmp = NULL;

  while(*head) {
    tmp = *head; /*tmp points the first node of the current list*/
    *head = (*head)->next;

    /*Insert tmp at the front of the reversed list.*/
    tmp->next = new_head;
    new_head = tmp;
  }

  *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("Initial List: ");
    print_list(head);

    reverse_linked_list(&head);

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

This program first takes input of integers and put them into a linked list using insert_front() function. Then the reverse_linked_list() is called to reverse the list.

Here is the output of the program.

reverse linked list output

Using Three Pointers

Instead of constructing a new list, we can reverse a linked list with the help of three pointers.

Logic to Reverse a Linked List Using There Pointer.

  1. Initialize three pointers, prev to NULL, cur to head and next to head->next.
  2. Until cur becomes NULL, assign next to next->next, cur->next to prev, prev to cur and cur to next.
  3. At the end point head to prev.

Here is the modified reverse_linked_list() function.

void reverse_linked_list(struct node **head) {
  struct node *prev = NULL;
  struct node *cur = NULL;
  struct node *next = NULL;

  cur = *head;
  if(*head) next = (*head)->next;

  while(cur) {
    next = next->next;
    cur->next = prev;
    prev = cur;
    cur = next;
  }
  *head = prev;
}

Read also: Sort a Linked List.

The post C Program to Reverse a Linked List appeared first on QnA Plus.

C Program to Swap Two Numbers

$
0
0

Here we’ll discuss about different techniques how we can swap two numbers. Swapping two numbers means exchanging the values of two variables. For example, if value of A is 5 and value of B is 10, then after swapping values of A and B would be 10 and 5 respectively.

Swap Two Numbers Using Third Temporary Number

We can swap two numbers with the help of another temporary number.

Logic

  1. Copy the value of first variable to a temporary variable.
  2. Assign the second variable to the first variable.
  3. Assign the temporary variable to the second variable.

Program

/*
 * File name: test.c
 * Compile: cc test.c -o test
 * */
#include <stdio.h>

void main()
{
  unsigned int A, B, tmp;

  printf("Enter the first variable (A): ");
  scanf("%d", &A);
  
  printf("Enter the second variable (B): ");
  scanf("%d", &B);
  
  printf("\nBefore swapping:\n");
  printf("A = %u, B = %u\n", A, B);
  
  /*Swapping A and B*/
  tmp = A;
  A = B;
  B = tmp;
  
  printf("Before swapping:\n");
  printf("A = %u, B = %u\n", A, B);
}

This program first takes input of two variables A and B and prints them before swapping. Then it swaps them using the above logic and prints them again after swapping.

Here is the output.

Enter the first variable (A): 32
Enter the second variable (B): 45

Before swapping:
A = 32, B = 45
Before swapping:
A = 45, B = 3
2

Using Function Call

In the above example swapping logic is implemented in the main() itself. Here we’ll see how we can write a function that will swap the input arguments. To do that, we have to pass the arguments as reference instead of value.

Program

/*
 * File name: test.c
 * Compile: cc test.c -o test
 * */
#include <stdio.h>

void swap(unsigned int *a, unsigned int *b) {
  unsigned int tmp;
  
  tmp = *a;
  *a = *b;
  *b = tmp;
}

void main()
{
  unsigned int A, B, tmp;

  printf("Enter the first variable (A): ");
  scanf("%d", &A);
  
  printf("Enter the second variable (B): ");
  scanf("%d", &B);
  
  printf("\nBefore swapping:\n");
  printf("A = %u, B = %u\n", A, B);
  
  /*Swapping A and B by calling a function swap()*/
  swap(&A, &B);
  
  printf("Before swapping:\n");
  printf("A = %u, B = %u\n", A, B);
}

Here we called the function swap() with references of A and B. Output would be same here.

Swap two Variables Without Using Third One

In the above examples, we took help of a third temporary variable. Here we’ll see how we can achieve the same without using a third variable.

Logic

  1. Add two variables and assign the summation to the first variable.
  2. Subtract the second variable from the first one and assign the result to the second variable. In this step second variable gets the value of first one.
  3. Subtract the second variable from the first one and assign the result to the first variable. In this step first variable gets the value of second one.

Program

/*
 * File name: test.c
 * Compile: cc test.c -o test
 * */
#include <stdio.h>

void main()
{
  unsigned int A, B, tmp;

  printf("Enter the first variable (A): ");
  scanf("%d", &A);
  
  printf("Enter the second variable (B): ");
  scanf("%d", &B);
  
  printf("\nBefore swapping:\n");
  printf("A = %u, B = %u\n", A, B);
  
  /*Swapping A and B */
  A = A + B;
  B = A - B;
  A = A - B;
  
  printf("Before swapping:\n");
  printf("A = %u, B = %u\n", A, B);
}

Here the swapping logic does not use a third variable. It works in most cases. But it has some problem.

Problem with This Logic

But consider the following output.

Enter the first variable (A): 4294967001
Enter the second variable (B): 4294967100

Before swapping:
A = 4294967001, B = 4294967100
Before swapping:
A = 4294967001, B = 99

From this output we can see that numbers are not swapped properly. When we added two variables (A+B), the result became 8589934101. But an unsigned integer can not store a value bigger than 4294967295. So when we assigned the summation to A, the information is lost. After that we could not recover the original values.

Solutions

We solve the above problem in various ways. We can slightly change this 3 line snippet

A = A + B;
  B = A - B;
  A = A - B;

to

A = A + B - (B = A);

Here we are not storing the summation to any variable. (B=A) will assign A to B and then subtracted from the summation. Intermediate results of the right side of the expression will be stored in registers. The final result will be stored in variable A.

If we run this problem, the output would be changed like this.

Enter the first variable (A): 4294967001
Enter the second variable (B): 4294967100

Before swapping:
A = 4294967001, B = 4294967100
Before swapping:
A = 4294967100, B = 4294967001

We can also solve this problem with XOR (Exclusive OR) operation.

Swapping Two Numbers using XOR Operation

The logic is very similar to the summation one. Here is the program.

/*
 * File name: test.c
 * Compile: cc test.c -o test
 * */
#include <stdio.h>

void main()
{
  unsigned int A, B, tmp;

  printf("Enter the first variable (A): ");
  scanf("%d", &A);
  
  printf("Enter the second variable (B): ");
  scanf("%d", &B);
  
  printf("\nBefore swapping:\n");
  printf("A = %u, B = %u\n", A, B);
  
  /*Swapping A and B */
  A = A ^ B;
  B = A ^ B;
  A = A ^ B;
  
  printf("Before swapping:\n");
  printf("A = %u, B = %u\n", A, B);
}

One integer is enough to store the result of XOR Operation of two integer. So there won’t be any overflow problem.

The post C Program to Swap Two Numbers appeared first on QnA Plus.

C Program to Delete the First Node of a Linked List

$
0
0

Here we’ll see how write C program to delete the first node of a linked list. Head always points to the first node. Head will move to where the first node is currently pointing to. First node can either point to the second node or to NULL in case the first node is the only node in the linked list. After moving the head, we can free up the memory of the first node.

Logic to Delete First Node of a Linked List.

  1. If head is NULL, return. There is no element in the linked list.
  2. Assign the head pointer to a temporary variable, tmp.
  3. Move the head to the next node. If the linked list has only one node, head will move to NULL.
  4. Delete the temporary pointer, tmp. As tmp is pointing to the first node, first node will be deleted.
Delete the first node of a linked list

Read also: Delete any node from a linked list.

The Program

/*File: test.c*/

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

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

/*Delete the first node of a linked list.*/
void delete_first_node(struct node **head) {
  struct node *tmp;

  /*Linked list does not exist or the list is empty*/
  if(head == NULL || *head == NULL) return;
  
  /*Storing the head to a temporary variable*/
  tmp = *head;
  
  /*Moving head to the next node*/
  *head = (*head)->next;
  
  /*Deleting the first node*/
  free(tmp);
}

/*Print the linked list*/
void print_list(struct node *head) {
    
    printf("H->");

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

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

/*Insert an element at the front of the list*/
void insert_front(struct node **head, int value) {
    
    struct node * new_node = NULL;

    /*Allocating memory for the new node*/
    new_node = (struct node *)malloc(sizeof(struct node));

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

    new_node->val = value;

    /*Pointing the new node to where head is currently pointing to*/
    new_node->next = *head;

    /*Pointing head to new node.*/
    *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 Linked List: ");
    print_list(head);
    
    delete_first_node(&head);
    
    printf("Linked List after first node deleted: ");
    print_list(head);
}

The above program first creates a linked list and then calls the delete_first_node() to delete the first node.

We passed head as double pointer to the delete_first_node() function because head will get changed from inside the function. To change a pointer from a function we need to pass that as double pointer.

Here is the output.

Delete first node of a linked list output

The post C Program to Delete the First Node of a Linked List appeared first on QnA Plus.

C Program to Delete the Last Node of a Linked List

$
0
0

Here we’ll see how to delete the last node of a linked list. The last node always points to NULL. To delete that, we have to traverse up to last node. We have to point the second last node to NULL and free memory of the last node. After deletion the second last node will become the new last node.

Delete the last node of a linked list.

Logic to Delete the Last Node of a Linked List

  1. If head points to NULL, return. The linked list is empty – there is no node.
  2. If the first node points to NULL – there is only one node in the linked list, delete the first node and assign NULL to head.
  3. Point prev to first node and cur to second node.
  4. Keep moving prev and cur (prev = prev->next, cur = cur->next) until cur->next is NULL.
  5. If cur->next is NULL, set prev->next equals to NULL and delete cur.

Read also: Delete any node from a linked list.

Read also: Delete the first node of a linked list.

The Program

/*File: test.c*/

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

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

/*Delete the last node of a linked list.*/
void delete_last_node(struct node **head) {
  struct node *prev = NULL, *cur = NULL;

  /*Linked list does not exist or the list is empty*/
  if(head == NULL || *head == NULL) return;
  
  /*If there is only one node in the list*/
  if((*head)->next == NULL) {
    free(*head);
    *head = NULL;
  }
  
  prev = *head;
  cur = prev->next;
  
  while(cur->next) {
    prev = prev->next;
    cur = cur->next;
  }
  
  prev->next = NULL;
  free(cur);
}

/*Print the linked list*/
void print_list(struct node *head) {
    
    printf("H->");

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

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

/*Insert an element at the front of the list*/
void insert_front(struct node **head, int value) {
    
    struct node * new_node = NULL;

    /*Allocating memory for the new node*/
    new_node = (struct node *)malloc(sizeof(struct node));

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

    new_node->val = value;

    /*Pointing the new node to where head is currently pointing to*/
    new_node->next = *head;

    /*Pointing head to new node.*/
    *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 Linked List: ");
    print_list(head);
    
    delete_last_node(&head);
    
    printf("Linked List after last node deleted: ");
    print_list(head);
}

This program first creates a linked list and then call the delete_last_node() function. The delete_last_node() takes a linked list a input and deletes the last node. Here we passed head as double pointer because head might get changed from inside the function if there is only one node in the list. To change a pointer from inside a function we need to pass that as double pointer.

Here is the output of the above program.

delete the last node of a linked list output

The post C Program to Delete the Last Node of a Linked List appeared first on QnA Plus.


C Program to Move the Last Node to the Front of a Linked List

$
0
0

Here we’ll see how to write C Program to move the last node to the front of a linked list. We can do that just by re-arranging the pointers. No need to create or delete any node.

Move last node to front of a linked list

Logic to Move the Last Node to the Front

  1. If the linked list is empty or has only one element, then return. If the list has only one element, then the first node and the last node are basically same.
  2. Point prev to the first node and cur to the second node.
  3. Keep moving both prev and cur to the next nodes until cur->next becomes NULL. cur->next pointing to NULL means cur pointing to the last node and prev pointing to the second last node.
  4. Point the second last node to NULL (prev->next = NULL), last node to the first node (cur->next = head). And assign head where cur is pointing to (head = cur).

The Program

/*File: test.c*/

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

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

/*Move the last node to the front.*/
void move_last_node_to_front(struct node **head) {
  struct node *prev = NULL, *cur = NULL;

  /*Return if there is no node or only one node*/
  if(head == NULL || *head == NULL || (*head)->next == NULL) return;
  
  prev = *head;
  cur = prev->next;
  
  /*Going to the last node*/
  while(cur->next) {
    prev = prev->next;
    cur = cur->next;
  }
  
  prev->next = NULL;
  cur->next = *head;
  *head = cur;
}

/*Print the linked list*/
void print_list(struct node *head) {
    
    printf("H->");

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

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

/*Insert an element at the front of the list*/
void insert_front(struct node **head, int value) {
    
    struct node * new_node = NULL;

    /*Allocating memory for the new node*/
    new_node = (struct node *)malloc(sizeof(struct node));

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

    new_node->val = value;

    /*Pointing the new node to where head is currently pointing to*/
    new_node->next = *head;

    /*Pointing head to new node.*/
    *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 Linked List: ");
    print_list(head);
    
    move_last_node_to_front(&head);
    
    printf("Linked List after movinf last node to front: ");
    print_list(head);
}

This program first takes input of some numbers to create the linked list. Then it calls the move_last_node_to_front() function to move the last node to the front.

Here is the output.

Move the last node to the front of a linked list output

From the output we can see that initially 43 was the last node. After the move_last_node_to_front() function call, it became the first node of the linked list.

Read also: Insert an element to a linked list.

The post C Program to Move the Last Node to the Front of a Linked List appeared first on QnA Plus.

C Program to Set, Clear and Toggle a Bit

$
0
0

In this article we saw how to check a particular bit of a number. Here we’ll see how to set, clear or toggle a bit of a number.

Setting a Bit

Setting a bit means making that bit 1 irrespective of the previous value of that bit.

We can use bitwise operation OR (|) to set a particular bit.

OR operation chart

From the OR (|) operation chart, we can see that if we do OR (|) between 1 and any other bit, the result becomes 1. But if we do OR (|) operation between 0 and any other bit, the bit remains unchanged.

The binary representation of 39653 is 1001101011100101. Now say we want to set the 8-th (starting from 0) bit which is currently 0. First we have to find out a number whose 8-th bit is 1 and others are 0. If we do OR (|) with such a number, the 8-th will become 1 and others will remain unchanged.

Set a bit
Set the 8-th Bit

The Program

#include <stdio.h>

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

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

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

    printf("Binary of %d: ", num);
    binary(num);
    
    printf("\nEnter a bit position to set: ");
    scanf("%d", &pos);
    
    num = num | (0x01 << pos);
    
    printf("After setting %d-th bit, the number becomes:\n", pos);
    
    printf("%d, Binary: ", num);
    binary(num);
    printf("\n");
}

This program takes an integer as input and prints that in binary form. Then it takes to bit position to set. It creates a number whose the specified bit is 1 and other bits are 0 (0x01 << pos). Then it did the OR (|) operation with the input number.

Here is the output.

Set a bit output

Clearing or Resetting a Bit

Clearing or setting a bit means making that bit 0 irrespective of the previous value of that bit.

We can use bitwise operation AND (&) to set a particular bit.

From the AND (&) operation chart, we can see that if we do AND (&) between 0 and any other bit, the result becomes 0. But if we do AND (&) operation between 1 and any other bit, the bit remains unchanged.

Here also we’ll use the same number 39653 (1001101011100101) as example. Here we’ll clear the 7-th (starting from 0) bit which is currently 1. First we have to find out a number whose 7-th bit is 0 and others are 1. If we do AND (&) with such a number, the 7-th will become 0 and others will remain unchanged.

Clear a bit
Clear the 7-th Bit

The Program

#include <stdio.h>

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

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

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

    printf("Binary of %d: ", num);
    binary(num);
    
    printf("\nEnter a bit position to clear: ");
    scanf("%d", &pos);
    
    num = num & ~(0x01 << pos);
    
    printf("After clearing %d-th bit, the number becomes:\n", pos);
    
    printf("%d, Binary: ", num);
    binary(num);
    printf("\n");
}

This program takes an integer as input and prints that in binary form. Then it takes to bit position to clear. It creates a number whose the specified bit is 0 and other bits are 1 (~(0x01 << pos)). Then it did the AND (&) operation with the input number.

Here is the output

Toggling a Bit

Toggling a bit means altering the bit value. If the bit is 0, make it 1. If the bit is 1, make it 0.

We can use bitwise operation XOR (^) to toggle a particular bit.

From the XOR (^) operation chart, we can see that if we do XOR (^) between 1 and any other bit, bit value alters. But if we do XOR (^) operation between 0 and any other bit, the bit remains unchanged.

So with our example number 39653 (1001101011100101), we’ll toggle the 7-th (starting from 0) bit which is currently 1. First we have to find out a number whose 7-th bit is 1 and others are 0. If we do XOR (^) with such a number, the 7-th will become 0 and others will remain unchanged.

If we do the same operation on 8-th bit, the bit will become 1 from 0.

Toggle a bit

The Program

#include <stdio.h>

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

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

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

    printf("Binary of %d: ", num);
    binary(num);
    
    printf("\nEnter a bit position to toggle: ");
    scanf("%d", &pos);
    
    num = num ^ (0x01 << pos);
    
    printf("After toggling %d-th bit, the number becomes:\n", pos);
    
    printf("%d, Binary: ", num);
    binary(num);
    printf("\n");
}

This program first prints the input number in binary form. Then it takes to bit position to set. It creates a number whose the specified bit is 1 and other bits are 0 (0x01 << pos). Then it did the XOR (^) operation with the input number.

Here is the output.

Toggle a bit output

The post C Program to Set, Clear and Toggle a Bit appeared first on QnA Plus.

C Program to Toggle Bits

$
0
0

Here we’ll see how to write C program to toggle all bits or a particular bit or all but a particular bit of a number.

Toggle All Bits of a Number

We can toggle all bits of a number using NOT (~) bitwise operation. Doing NOT (~) operation on a number toggles all of its bits.

#include <stdio.h>

void binary(unsigned int n)
{
	unsigned int mask = 0x80000000;
    while(mask) {
	  printf("%d", (n&mask)?1:0);
	  mask = mask >> 1;
	}
}

void main()
{
    unsigned int num = 0;

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

    printf("Binary represntation of the input number:\n");
    binary(num);
    
    num = ~num;
    
    printf("\n\nAfter toggling all bits of the number:\n");
    binary(num);
    printf("\n");
}

This program takes an unsigned integer as input and prints the 32-bits of that number. Then it does NOT (~) operation on the number to toggle all bits. After toggling it prints the bits of the number.

Here is the output.

Toggle all bits output

Toggle a Particular Bit

In the previous article I discussed about how to toggle a particular bit of a number in detail. Here we’ll see the program.

#include <stdio.h>

void binary(unsigned int n)
{
	unsigned int mask = 0x80000000;
    while(mask) {
	  printf("%d", (n&mask)?1:0);
	  mask = mask >> 1;
	}
}

void main()
{
    unsigned int num = 0;
	int pos = 0;
	
    printf("Enter an integer: ");
    scanf("%d", &num);

    printf("Binary represntation of the input number:\n");
    binary(num);
    
    printf("\nEnter a bit position to toggle (0-31): ");
    scanf("%d", &pos);
    
    num = num ^ (0x01 << pos);
    
    printf("\n\nAfter toggling %d-th bit of the number:\n", pos);
    binary(num);
    printf("\n");
}

Here is the output.

Toggle a particular bit

Toggle All but a Particular Bit

Say we want to toggle all bits of an number but the k-th bit should remain unchanged. To do that we have to first toggle the k-th bit and then toggle all bits. So the k-th would be toggled twice. That means that will remain unchanged. Other bits would be toggled once.

#include <stdio.h>

void binary(unsigned int n)
{
	unsigned int mask = 0x80000000;
    while(mask) {
	  printf("%d", (n&mask)?1:0);
	  mask = mask >> 1;
	}
}

void main()
{
    unsigned int num = 0;
	int pos = 0;
	
    printf("Enter an integer: ");
    scanf("%d", &num);

    printf("Binary represntation of the input number:\n");
    binary(num);
    
    printf("\nEnter a bit position that will remain unchanged (0-31): ");
    scanf("%d", &pos);
    
    num = ~(num ^ (0x01 << pos));
    
    printf("\n\nAfter toggling all but %d-th bit of the number:\n", pos);
    binary(num);
    printf("\n");
}

Here is the output.

Toggle all but a particular bit

In this example, all bits of the input number toggled expect bit 7 (starting from 0)

The post C Program to Toggle Bits appeared first on QnA Plus.

Left and Right Rotate Bits of a Number in C

$
0
0

Here we’ll see how to write C program to left or right rotate bits of a number. For example, an unsigned integer consists of 32-bit. Number 2591458749 is represented as 10011010011101101000010110111101 in binary. The diagram below shows how the bits of that number will look like after rotating 8 bits.

Left and right rotate bits of a number

Logic to Left Rotate Bits

Say we want to left rotate an integer of size 32 bits by n bits.

  1. Create a number, num1 by left shifting n bits. (num1 = num << n)
  2. Create another number, num2, by right shifting (32-n) bits. (num2 = num >> (32-n))
  3. The result is num1 OR (|) num2.

Logic to Rotate Rotate Bits

Logic is very similar if we want to right rotate an integer of size 32 bits by n bits.

  1. Create a number, num1 by right shifting n bits. (num1 = num >> n)
  2. Create another number, num2, by left shifting (32-n) bits. (num2 = num << (32-n))
  3. The result is num1 OR (|) num2.

The Program

#include <stdio.h>

void binary(unsigned int n)
{
	unsigned int mask = 0x80000000;
    while(mask) {
	  printf("%d", (n&mask)?1:0);
	  mask = mask >> 1;
	}
}

unsigned int left_rotate(unsigned int num, int n) {
  return (num << n) | (num >> (32 - n));
}

unsigned int right_rotate(unsigned int num, int n) {
  return (num >> n) | (num << (32 - n));
}

void main()
{
    unsigned int num = 0, result;
	int n = 0;
	
    printf("Enter an integer: ");
    scanf("%d", &num);

    printf("Binary represntation of the input number:\n");
    binary(num);
    
    printf("\nHow many bits to rotate (0-31)?: ");
    scanf("%d", &n);
    
    result = left_rotate(num, n);
    printf("\n\nAfter left rotating %d bits:\n", n);
    binary(result);
    
    result = right_rotate(num, n);
    printf("\n\nAfter right rotating %d bits:\n", n);
    binary(result);
    
    printf("\n");
}

This program takes an integer as input and prints the binary form of that number. Then it takes the input of how many bits to rotate. It rotates the number using left_rotate() and right_rotate() functions.

Here is the output.

Rotate bits output

The post Left and Right Rotate Bits of a Number in C appeared first on QnA Plus.

Brian Kernighan’s Algorithm to Count the Set Bits of a Number

$
0
0

To count all set bits of a number, we can loop through all the bits and check whether any bit is set. For example, an integer has 32 bits. We can check all 32 bits in a loop to count the set (1) bits. Here will see how we can improve this mechanism using Brian Kernighan’s algorithm.

Brian Kernighan’s Algorithm

Before under standing this algorithm, we have understand a basic property of binary number.

If we subtract a number by 1, then all bits starting from the right most 1 will get altered.

For example, binary representation of 2392 is 100101011000. And binary representation of 2391 (2392 -1) is 100101010111.

Brian Kernighan's algorithm

From the above diagram, we can see that right most 1 is located at 3-rd bit position of 2392. An in 2391 (one less 2392) all right bits starting from the 3-rd position gets altered. This theory holds for any number.

Now if we do bitwise AND (&) operation between 2392 and 2391, the right most set bit (1) will become 0 in the result.

Removing right most 1

From the diagram above we can see that the right most 1 (at 3-rd bit position) becomes 0.

To generalize this behavior, we can say that the operation n & (n-1) removes one set bit from the result. If we do the same operation again with the result, then one more set bit would be removed. If we continue this as many times as the number of set bits, the result would become zero. So, the number of iterations is equal to the number of set bits.

So for an integer we don’t have to iterate 32 times, but as many times as the number of set bit.

C Implementation of Brian Kernighan’s Algorithm

#include <stdio.h>

int count_set_bits(unsigned int n) {
  int count = 0;
  while(n) {
    count++;
    n = n & (n-1);
  }
  
  return count;
}

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

void main()
{
    unsigned int num, result;

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

    printf("Binary of %d: ", num);
    binary(num);
    
    result = count_set_bits(num);
    
    printf("\nNumber of set bits in %d is %d.\n", num, result);
}

This program takes an integer as input and prints that in binary format. Then it counts the number of set bits by calling count_set_bits() function.

Here is the output.

Brian Kernighan's program output

Recursive Implementation

We can implement the same algorithm as recursive function also.

Logic

  1. If n is 0, return 0. There is no set bit in the input number n.
  2. If n & (n-1) is 0, then there is exactly on set bit in n. So return 1 in this case.
  3. If n & (n-1) is not 0, there are multiple set bits in n. So recursively get get the set bit count for n&(n-1). So the result would the the count from recursive call plus 1. Because at this stage exactly one set bit is cleared by n&(n-1) operation.

Here is the recursive version of count_set_bits() function.

int count_set_bits(unsigned int n) {
  unsigned int res;
  
  if (n == 0) return 0;
  
  res = n & (n-1);
  if (res == 0) return 1;
  
  return count_set_bits(res) + 1;
}

The post Brian Kernighan’s Algorithm to Count the Set Bits of a Number appeared first on QnA Plus.

Viewing all 93 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>