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

How to Implement Merge Sort in C?

$
0
0

Merge sort is efficient, general-purpose sorting algorithm. Unlike bubble sort or insertion sort, it is usable in most practical cases. Merge sort is divide and conquer algorithm. Here we’ll see how to implement merge sort in C programming language. We’ll also analyze its performance in various conditions.

Merge Sort Algorithm

Merge sort is divide and conquer algorithm.

  1. Repeatedly divide the input array into sub-arrays until each sub-array contains one element.
  2. Repeatedly merge the sub-arrays such that the merged the sub-array becomes sorted until there is one sub-array.

Step 1 is the divide part of the algorithm. At every stage, each sub-array will be divided into two parts. At the beginning, the whole array is the first sub-array that will be divided. If a sub-array contains even number of elements then the divided sub-arrays will also have equal number of elements. Otherwise, one divided sub-array will have one more element than the other divided sub-array. We’ll continue this process until all sub-arrays contain only one element. As the sub-arrays have one element, they are trivially sorted.
Step 2 is the conquer part, we’ll keep merging the sorted sub-arrays, such that the merged sub-arrays also be sorted. We’ll continue this process until we get only one sub-array which will contain all the elements of the starting array.

Graphical Illustration of Merge Sort

Graphical Illustration of Merge Sort
The above diagram shows how merge sort works. The array has seven elements to begin with. First the array is divided into two sub-arrays, one with 4 elements and other with 3 elements. Then they further divided into four sub-arrays. And finally in the next stage, all sub-arrays have only one element. So, all sub-arrays are sorted (array with one element is always sorted). Divide part ends here and the conquer part begins. Single element sub-arrays are merged to become two element sorted sub-arrays. Similar process continues until all elements are merged into one sorted sub-array.

Top-down Implementation of Merge Sort in C

Here is the top down implementation of merge sort in C. In top-down approach, the array is divided recursively into sub-arrays until the size of the sub-arrays becomes 1. Array of size size 1 is sorted by default. Then the sorted sub-arrays are merged continuously such that the merged sub-arrays become sorted. This process continues until all sub-arrays are merged into one array. Top down implementation of merge sort is more popular, widely used and easy to under stand method.

#include <stdio.h>

void merge(int *arr, int start, int mid, int end)
{
  int * tmp_arr = NULL;
  int i = 0;
  int l1 = start;
  int r1 = mid;
  int l2 = mid + 1;
  int r2 = end;

  tmp_arr = (int *)malloc(sizeof(int) * (end - start + 1));

  while((l1 <= r1) && (l2 <= r2))
  {
    if(arr[l1] < arr[l2])
      tmp_arr[i++] = arr[l1++];
    else
      tmp_arr[i++] = arr[l2++];
  }

  while(l1 <= r1) tmp_arr[i++] = arr[l1++];
  while(l2 <= r2) tmp_arr[i++] = arr[l2++];

  for(i = start; i <= end; i++) arr[i] = tmp_arr[i - start];

  free(tmp_arr);
}

void mergesort(int *arr, int start, int end)
{
  int mid = 0;

  if(start < end)
  {
    mid = (start + end) / 2;
    mergesort(arr, start, mid);
    mergesort(arr, mid+1, end);

    merge(arr, start, mid, end);
  }
}

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");

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

pppp

Bottom-up Implementation of Merge Sort in C

In bottom-up approach, the arrays of size n is considered as n sub-arrays of size one. Then the sub-arrays are merged to together such that the merged sub-arrays become sorted. This process continues until the size of the merge sub-array becomes equal to the original array size n. Here is the bottom-up implementation of merge sort in C.

void merge(int *arr, int start, int mid, int end)
{
  int tmp_arr[100];
  int i = 0;
  int l1 = start;
  int r1 = mid;
  int l2 = mid + 1;
  int r2 = end;

  while((l1 <= r1) && (l2 <= r2))
  {
    if(arr[l1] < arr[l2])
      tmp_arr[i++] = arr[l1++];
    else
      tmp_arr[i++] = arr[l2++];
  }

  while(l1 <= r1) tmp_arr[i++] = arr[l1++];
  while(l2 <= r2) tmp_arr[i++] = arr[l2++];

  for(i = start; i <= end; i++) arr[i] = tmp_arr[i - start];
}

int min(int a, int b)
{
  return (a < b)?a:b;
}

void mergesort(int *arr, int len)
{
  int width = 0, i = 0;

  for (width = 1; width < len; width = width * 2)
  {
    for(i = 0; i < len; i = i + 2*width)
    {
      merge(arr, i, min(i + width, len), min(i + 2*width, len));
    }
  }
}

ssss

Performance of Merge Sort

Running time of merge sort in Big-O notation is O(n log n) for best, average and worst case scenarios. If we consider that merge sort take T(n) time to sort n number of elements, then the equation T(n) = 2T(n/2) + n follows the definition of the algorithm, where T(n/2) to sort the sub-array and n to merge two sorted sub-arrays. Applying master theorem, the running time in Big-O notation becomes O(n log n).

Diagram below show an experimental result to demonstrate the performance of the merge sort for different types of input arrays. It shows how number of comparisons increases with the increase of number of inputs.

merge sort performance

In this experiment we used three types of array. The numbers are randomly distributed in the first array, numbers are already sorted in the second array and numbers are reversely sorted in the third array. Number of inputs increase by 1000 in every iteration staring from 1000. The growth rate of comparisons required is O(n log n) in all cases but actual number of comparisons differs. In case of the random array, the number of comparisons is close to n * log n, where n is the number of inputs. But in case of already sorted array or reversely sorted array, the actual number of comparisons is close to (n * log n ) / 2. If the array is sorted, merge sort takes half number of comparisons compared to a random array.

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


How to Implement Quick Sort in C?

$
0
0

Quick Sort is an efficient sorting algorithm developed by Tony Hoare in 1959. It is still a commonly used sorting algorithm in most practical cases. If implemented properly, it is two or three times faster than other efficient sorting algorithms like merge sort or heap sort. Here we’ll see how to implement this sorting algorithm in C programming language. And also we’ll discuss about the algorithm and analyze the performance in various conditions.

Quick Sort Algorithm

Quick sort is a divide and conquer algorithm which is generally implemented using recursive function.

  1. Select an element from the array as pivot.
  2. Partition the array. One partition will contain all the elements that are less than the pivot. Another partition will contain all elements that are greater than the pivot.
  3. Apply this procedure recursively with these two partitions.

Recursion will stop when a partition will have 1 or 0 element. This is the base case of the recursion. Performance of merge sort is heavily dependent on the selection of the pivot. Different strategies are taken based on the condition to select the pivot to get better performance.

  1. First element of the partition is selected as pivot.
  2. Last Element of the partition is selected as pivot.
  3. Random element of the partition is selected as pivot.
  4. Median of first, middle and last element of the partition is selected as pivot.

Graphical Illustration of Quick Sort

quick sort graphical illustration

The diagram above shows how quick sort works. First one element is selected as pivot. In this case 4 is selected as pivot in the first iteration. The array is than sub-divided into two partitions. Left partition contains all the element which are less than the pivot 4 and the right partition contains all the elements which are greater than 4. If we continue this procedure after 2 more iterations, the array will become sorted.

Implementation of Quick Sort in C

Here is the complete C program that implements the quick sort.

#include <stdio.h>

int partition(int *arr, int start, int end){

  int pivot, tmp, i, j;

  if(start >= end) return -1;

  pivot = start;
  i = start;
  j = end;

  while(i < j)
  {
    while(arr[i] <= arr[pivot] && i < end) i++;
    while(arr[j] > arr[pivot]) j--;

    if( i < j)
    {
      tmp = arr[i];
      arr[i] = arr[j];
      arr[j] = tmp;
    }
  }

  tmp = arr[pivot];
  arr[pivot] = arr[j];
  arr[j] = tmp;

  return j;
}

void quicksort(int *arr, int start, int end){

  int p = 0;

  if(start < end)
  {
    p = partition(arr, start, end);
    quicksort(arr, start, p-1);
    quicksort(arr, p+1, end);
  }
}

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");

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

 

bbbb

Performance of Quick Sort

Worst Case: Running time of quick sort in worst case scenario is O(n2). Worst case scenario occurs when pivot divides two partitions of size 0 and n-1, most unbalanced partition. In every iteration one partition would not have any element and other partition will have remaining n-1 elements. This situation occurs when smallest or biggest element is selected as pivot. One example of such situation is when we apply quicksort on a sorted array and first or last element is selected as pivot.

Best Case: Running time of quick sort in best case scenario is O(n log n). Worst case scenario occurs when pivot divides two partitions of equal number of elements in every iteration. One example of such situation is when we apply quicksort on a sorted array and the middle element is selected as pivot.

Average Case: Running time of quick sort in average case scenario is O(n log n). In average case the partitions may not be equal but average size of the partitions of all iterations will be equal. Average condition occurs when we apply quicksort on a randomly ordered array.

The diagram below shows an experimental result how quicksort performs in various conditions.

quick sort performance

We can see that the actual number of comparisons in worst case is much higher than the best or average case. Another thing to notice that the growth rate of number of comparisons with respect to the number of inputs is also much much higher in worst case than best or average case.

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

How to Implement Shell Sort in C Programming?

$
0
0

Shell Sort (aka shellsort) can be thought as an improvement over insertion sort. To understand shell sort, we have to recall how insertion sort works. In insertion sort at any moment, the whole array is sub-divided in two sections, one is sorted and another is not. One element is picked from the unsorted section and compares with the elements of sorted section one by one to get the right position for that element. We may need to compare with all elements of the sorted section to get the right position of the new element. This might happen for many or most of the elements. To improve this situation, in shell sort the insertion sort is done with the far apart elements first. In this process, some out-of-place elements will come to their right locations without needing too many comparisons. Then the gap between the elements, insertion sort is applied with, is reduced gradually. The algorithm stops after applying the insertion sort with gap 1.

Shell Sort Implementation in C

#include <stdio.h>

void shellsort(int *arr, int n){

  int tmp, gap, i, j;

  for (gap = n/2; gap > 0; gap /= 2)
  {
    for(i = gap; i < n; i++)
    {
      tmp = arr[i];
      for (j = i; j >= gap && arr[j - gap] > tmp; j -= gap)
      {
        arr[j] = arr[j - gap];
      }
      arr[j] = 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");

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

 

Performance of Shell Sort

Running time of shell sort is still a subject of study but in most cases it is O(N2). Its performance is heavily dependent on the selection of gaps. But in most cases, the actual number of comparisons required is much less than the insertion sort.
The diagram below shows an experimental result how shell sort performs with respect to insertion sort with the increase of number of elements. Randomly ordered arrays were used for this experiment.

Shell Sort performance with respect to insertion sort

From the graph, we can see how performance improved significantly if we sort the far apart elements first then reduce the gap gradually till 1 than to apply insertion with gap 1.

Note: Similar concept can be applied on top of bubble sort also. We can apply bubble sort on far apart elements, then gradually reduce the gap to 1. This sort is also called shell sort.

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

C Program to Find Second Largest Element in an Array

$
0
0

Here we’ll see the possible solutions of finding the second largest element in an array.

By Sorting the Array:

Easy solution that I can think of to find the second largest element in an array is to first sort the array and then pick the second or second last element of the array depending on whether the array is sorted in descending or ascending order.
In the following program we’ll first sort the array in ascending order using bubble sort. Once the array is sorted, then the second last element will be the second largest element.

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

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;
      }
    }
  }
}

int main()
{
  int n, i;
  int *arr = NULL;
  printf("Enter number of elements: ");
  scanf("%d", &n);

  arr = (int *)malloc(n*sizeof(int));
  if (arr == NULL)
  {
    printf("Memory allocation failed.\n");
    return 0;
  }

  for (i = 0; i < n; i++)
  {
    printf("Enter %d-th element: ", i+1);
    scanf("%d", arr+i);
  }
  printf("Input array: ");
  for (i = 0; i < n; i++)
  {
    printf(" %d", arr[i]);
  }
  printf("\n");

  /*Doing bubble sort*/
  bubble_sort(arr, n);

  printf("Second largest element of the array: %d\n", arr[n-2]); /*(n-1)-th element is the last one, (n-2)-th element is the second last.*/
  return 1;
}

Output of the Program:

Enter number of elements: 6
Enter 1-th element: 32
Enter 2-th element: 1
Enter 3-th element: 34
Enter 4-th element: 24
Enter 5-th element: 5
Enter 6-th element: 76
Input array:  32 1 34 24 5 76
Second largest element of the array: 34

Though this is very simple solution, it has some drawback. It time complexity is O(n2) whereas O(n) solution is possible. O(n2) is very inefficient compared to O(n).

Without Sorting

The following solution is by traversing the array once.

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


int main()
{
  int n, i;
  int largest, second_largest;
  int *arr = NULL;
  printf("Enter number of elements: ");
  scanf("%d", &n);

  arr = (int *)malloc(n*sizeof(int));
  if (arr == NULL)
  {
    printf("Memory allocation failed.\n");
    return 0;
  }

  for (i = 0; i < n; i++)
  {
    printf("Enter %d-th element: ", i+1);
    scanf("%d", arr+i);
  }
  printf("Input array: ");
  for (i = 0; i < n; i++)
  {
    printf(" %d", arr[i]);
  }
  printf("\n");

  largest = arr[0];
  second_largest = largest;

  for (i = 1; i < n; i++) { if(arr[i] > largest)
    {
      second_largest = largest;
      largest = arr[i];
    }
    else if (arr[i] > second_largest)
    {
      second_largest = arr[i];
    }
  }

  printf("Second largest element of the array: %d\n", second_largest);
  return 1;
}

In every step of the two largest elements are kept. The variables are initialized with the first element of the array assuming that it will be the desired result. From next iteration, the current element of the array is compared with the highest element. If the current element is highest element, the previous highest element will replace the second highest element and will be replaced by the current element. If the current element of the array is not greater than the highest element but greater than the second highest element, then it will replace the second highest element. At the end of the iteration, the variable second_largest will be the second highest element.

The post C Program to Find Second Largest Element in an Array appeared first on QnA Plus.

How to find position of a digit in a number in C programming?

$
0
0

This program will find out the position of a digit in a number. For example digit 4 is present in 41234253 at 4th and 8th positions from left.
Logic is simple, we start with the number say 41234253 and do modulo operation with 10. We’ll get the last digit 3. If it matches the digit (4 here) we are comparing with then we can say the position is 1. If not we can do same thing with remaining digits from the number (4123425). To get the remaining digits we do integer div operation with 10. In every iteration we’ll increase the position count by 1. Here is the program.

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

int main()
{
  int n, d;
  int number, r, i;
  int found = 0;

  printf("Enter a number: ");
  scanf("%d", &n);

  printf("Enter a digit to find (0 to 9): ");
  scanf("%d", &d);

  while(d < 0 || d > 9) {
    printf("Wrong entry\n");
    printf("Enter a digit to find (0 to 9): ");
    scanf("%d", &d);
  }
  number = n;
  i = 1;
  while(number) {
    r = number % 10;
    if(r == d) {
      found = 1;
      printf("Digit %d found at position %d.\n", d, i);
    }
    i++;
    number = number / 10;
  }
  if(!found) printf("Digit %d is not present in %d\n", d, n);
  return 1;
}

He is the Output:

The output:
[qnaplus@localhost home]$ ./test.out
Enter a number: 41234253
Enter a digit to find (0 to 9): 4
Digit 4 found at position 4.
Digit 4 found at position 8.
[qnaplus@localhost home]$ ./test.out
Enter a number: 23945
Enter a digit to find (0 to 9): 7
Digit 7 is not present in 23945

The post How to find position of a digit in a number in C programming? appeared first on QnA Plus.

C Program to Sleep in Milliseconds

$
0
0

We don’t have millisecond level control in the sleep() function. But in Linux we can implement our own function that will take duration in milliseconds as input and sleep for that duration.

Using usleep()

The usleep() function takes input as micro seconds. We can write our own function that’ll take input as millisecond. We can simply pass that value multiplying by 1000 to usleep() function.

#include <unistd.h>

int msleep(unsigned int tms) {
  return usleep(tms * 1000);
}

This implementation is good enough but only thing is that the usleep() function is now deprecated. We have few other options also.

Using nanosleep()

We can implement our msleep() function using nanosleep() which takes timespec structure as input. It has nano second level control. We can convert the input milliseconds into second and nanoseconds before calling the nanosleep() function.

#include <errno.h>
#include <time.h>

int msleep(long tms)
{
    struct timespec ts;
    int ret;

    if (tms < 0)
    {
        errno = EINVAL;
        return -1;
    }

    ts.tv_sec = tms / 1000;
    ts.tv_nsec = (tms % 1000) * 1000000;

    do {
        ret = nanosleep(&ts, &ts);
    } while (ret && errno == EINTR);

    return ret;
}

You might notice that there is a loop around nanosleep() function. To understand this we need to understand the behavior of nanosleep() function.

From the man page of nanospleep.

nanosleep() suspends the execution of the calling thread until either at least the time specified in *req has elapsed, or the delivery of a signal that triggers the invocation of a handler in the calling thread or that terminates the process.
If the call is interrupted by a signal handler, nanosleep() returns -1, sets errno to EINTR, and writes the remaining time into the structure pointed to by rem unless rem is NULL. The value of *rem can then be used to call nanosleep() again and complete the specified pause.

If the function gets interrupted before elapsing the specified time, return value (ret) would be -1 and errno would be EINTR. As we passed ts as both parameters, remaining time will be set to the ts itself. We are calling the function with remaining time (modified ts). This process will continue until the total specified time is elapsed.

Using select()

We use select() function to detect whether any file descriptor is set. If we don’t pass any file descriptor, then it will time out after the specified time is elapsed. Here also we’ll have millisecond level control.

#include <sys/time.h>

void msleep(int tms)
{
    struct timeval tv;
    tv.tv_sec  = tms / 1000;
    tv.tv_usec = (tms % 1000) * 1000;
    select (0, NULL, NULL, NULL, &tv);
}

The post C Program to Sleep in Milliseconds appeared first on QnA Plus.

C Program to Reverse an Integer

$
0
0

Here we’ll see how to write C program to reverse an integer. The reverse_integer() function takes an integer like 5234569 and returns 9654325.

#include <stdio.h>

unsigned int reverse_integer(unsigned int in) {
  unsigned int out = 0;

  while(in) {
    out = out*10 + in%10;
    in /= 10;
  }

  return out;
}

int main(){
  unsigned int in = 0;

  printf("Enter a positive integer: ");
  scanf("%d", &in);

  printf("Reverse integer: %d\n", reverse_integer(in));

  return 0;
}

Output:

Enter a positive integer: 5234569
Reverse integer: 9654325

Logic:

The reverse_integer() function takes the last digit of “in” by doing modulo operation by 10. For example, if in is 5234569, 5234569 % 10 would be the last digit 9. Then we are adding this digit at the end of “out”. To do that we need to multiply out with 10 and then add the digit. For the next iteration we are removing the last digit from “in” by doing div operation by 10. The loop continues for all digits of original “in”.

The post C Program to Reverse an Integer appeared first on QnA Plus.

C Program to Reverse a String

$
0
0

Here we’ll see how to write a C program to reverse a string.

Solution 1

void reverse_string(char *input, char *output) {
  int len = 0, i = 0;

  if(input == NULL || output == NULL) return;

  len = strlen(input);

  for(i = 0; i < len; i++) {
    output[i] = input[len - i -1];
  }

  output[len] = '\0';
}

The reverse_string() function takes the input string as input parameter and reverses that into the output string. The last character of the input string is set as the first character of the output string, second last character of the input string as second character of output string and so on. Here the original string remains unchanged. The reversed string is set to the output string.

Solution 2

void reverse_string1(char *input) {
  int len = 0, i = 0;
  char tmp;

  if(input == NULL) return;

  len = strlen(input);

  for(i = 0; i < len / 2; i++) {
    tmp = input[i];
    input[i] = input[len - i -1];
    input[len - i -1] = tmp;
  }
}

Here the function reverse_string() iterates for as many times as half of the string length. In every iteration, two characters are swapped. In first iteration first and last characters are swapped, in second iteration second and second last characters are swapped and so on. Here the original string gets reversed.

The Complete Program

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

void reverse_string(char *input, char *output) {
  int len = 0, i = 0;

  if(input == NULL || output == NULL) return;

  len = strlen(input);

  for(i = 0; i < len; i++) {
    output[i] = input[len - i -1];
  }

  output[len] = '\0';
}

int main(){
  char str[] = "qnaplusdotcom";
  char rev[32];

  reverse_string(str, rev);
  
  printf("Original string: %s\n", str);
  printf("Reverse string: %s\n", rev);

  return 0;
}

The Output:

Original string: qnaplusdotcom
Reverse string: moctodsulpanq

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


C Program to Check Whether a String is Palindrome

$
0
0

Palindrome string is a string that reads the same in both directions, forward and backward. For example, “madam” reads the same from both directions. If you reverse a palindrome string, the reversed string would be the same as the original one. Here we’ll see how to write C program to check whether a string is a palindrome.

Method 1

int is_palindrome(char *str) {
  int len = 0, i = 0;
  if(str == NULL) return 0;

  len = strlen(str);

  for(i = 0; i < len/2; i++) {
    if(str[i] != str[len - i -1]) return 0;
  }

  return 1;
}

The above function, is_palindrome(), returns 1 if the input string is a palindrome, otherwise returns 0. It compares the first character with the last character, second character with second last character and so on. If any comparison fails (not equal), that means the string is not palindrome. It returns 0. If all comparisons pass, it returns 1.

Method 2

As I said earlier, the reverse of a palindrome string would be same as the original one. We can first reverse the string and check whether the original string is equal to the original one.

void reverse_string(char *input, char *output) {
  int len = 0, i = 0;

  if(input == NULL || output == NULL) return;

  len = strlen(input);

  for(i = 0; i < len; i++) {
    output[i] = input[len - i -1];
  }

  output[len] = '\0';
}

int is_palindrome(char *str) {
  char rev[128];

  if (str == NULL) return 0;

  reverse_string(str, rev);

  if(strcmp(str, rev) == 0) return 1;

  return 0;
}

The Complete Program

You can compile and run this program.

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


int is_palindrome(char *str) {
  int len = 0, i = 0;
  if(str == NULL) return 0;

  len = strlen(str);

  for(i = 0; i < len/2; i++) {
    if(str[i] != str[len - i -1]) return 0;
  }

  return 1;
}

int main(){
  char str[128];

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

  if(is_palindrome(str)) {
    printf("\"%s\" is a palindrome.\n", str);
  } else {
    printf("\"%s\" is not a palindrome.\n", str);
  }

  return 0;
}

Output of the above program:

Enter string: step on no pets
"step on no pets" is a palindrome.

Enter string: step on no pet
"step on no pet" is not a palindrome.

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

C Program to Check Whether a Number is Palindrome

$
0
0

Palindrome number reads the same from both directions, forward and backward. For example, “156434651” reads the same from both directions. If we reverse a palindrome number, the reversed number would be the same as the original one. Here we’ll see how to write a C program to check whether a number is a palindrome.

Method 1

int reverse_integer(int in) {
  int out = 0;

  while(in) {
    out = out*10 + in%10;
    in /= 10;
  }

  return out;
}

int is_palindrome(int n) {
  if(n == reverse_integer(n)) return 1;
  return 0;
}

Here first we reverse the number and compare that with the original one. If they are same, then the number is palindrome and the function, is_palindrome(), returns 1.

Method 2

int length(int n) {
  int l = 0;
  while(n) {
    l++;
    n /= 10;
  }
  return l;
}

/*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;
}

int is_palindrome(int n) {
  int len = 0, i = 0;

  len = length(n);

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

  return 1;
}

Here we compare the first digit of the number with the last digit, second digit with the second last digit and so on. If any comparison fails (not equal), that means the number is not a palindrome. The function, is_palindrome(), returns 0. If all comparisons pass, it returns 1.

The getdigit() is used to get a digit of any position of a number.

The Complete Program

You can compile and run this program.

#include <stdio.h>

int reverse_integer(int in) {
  int out = 0;

  while(in) {
    out = out*10 + in%10;
    in /= 10;
  }

  return out;
}

int is_palindrome(int n) {
  if(n == reverse_integer(n)) return 1;
  return 0;
}

int main(){
  int n = 0;

  printf("Enter a number: ");
  scanf("%d", &n);

  if(is_palindrome(n)) {
    printf("\"%d\" is a palindrome.\n", n);
  } else {
    printf("\"%d\" is not a palindrome.\n", n);
  }

  return 0;
}

Output of the above program:

Enter a number: 23456
"23456" is not a palindrome.

Enter a number: 5684865
"5684865" is a palindrome.

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

C Program to Print Fibonacci Series

$
0
0

Fibonacci series is a series of numbers where each number is the summation of two previous numbers. The first two numbers of Fibonacci series are 0 and 1. Here is an example of Fibonacci series: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377.

Loop Version

void print_fibonacci_series(int n) {
  int i = 0;
  int n1 = 0, n2 = 1, next;
  
  if (n < 1 ) return;
  
  if (n > 0) printf("0 ");
  if (n > 1) printf("1 ");
  
  for (i = 2; i < n; i++) {
    next = n1 + n2;
    printf("%d ", next);
    n1 = n2;
    n2 = next;
  }
}

The function, print_fibonacci_series(), prints a Fibonacci series of n numbers.

Recursive Version

int fibonacci(int n) {
  if (n < 2) return n;
  return fibonacci(n-1) + fibonacci(n-2);
}

void print_fibonacci_series(int n) {
  int i = 0;
  
  for (i = 0; i < n; i++) {
    printf("%d ", fibonacci(i));
  }
}

This version looks very simple but very inefficient. Number of add operations increases exponentially with the increase of number of elements in the series. For example, if you want to print 10 numbers, first version will have 10 (8 to be precise) add operations but this recursive version will have 133 add operations. If you want to print 20 numbers, first version will have 20 (18 to be precise) but the recursive version will have 17690 add operations. Now if you increase the number to 30, first version will have 30 add operations but second version will have 2178278 add operations. If you see how inefficient this version is. You need to be very careful about using it for bigger Fibonacci series.

The Complete Program

Here is the complete program that you can compile and run.

#include <stdio.h>

void print_fibonacci_series(int n) {
  int i = 0;
  int n1 = 0, n2 = 1, next;
  
  if (n < 1 ) return;
  
  if (n > 0) printf("0 ");
  if (n > 1) printf("1 ");
  
  for (i = 2; i < n; i++) {
    next = n1 + n2;
    printf("%d ", next);
    n1 = n2;
    n2 = next;
  }
}

int main(){
  int n = 0;
  
  printf("How many Fibonacci numbers?: ");
  scanf("%d", &n);

  printf("Fibonacci series:\n");
  print_fibonacci_series(n);
  return 0;
}

Output of the program:

How many Fibonacci numbers?: 15
Fibonacci series:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

The post C Program to Print Fibonacci Series 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.

C Program to Print Current Date and Time

$
0
0

Quite often we need to print the current date and time from our program. For example, when we write log messages, we generally attach the timestamp with every message. Here we’ll see how to write a C program to print the current date and time.

#include <stdio.h>
#include <time.h>

int main(){
  
  char cur_time[128];
  
  time_t      t;
  struct tm*  ptm;
  
  t = time(NULL);
  ptm = localtime(&t);
    
  strftime(cur_time, 128, "%d-%b-%Y %H:%M:%S", ptm);
  
  printf("Current date and time: %s\n", cur_time);
  
  return 0;
}

The time() function returns the number of seconds elapsed since the Epoch, 1970-01-01 00:00:00 +0000 (UTC). Function localtime() takes this number and converts it in broken-down time structure. Broken-down time, which is stored in the structure ptm, looks like:

struct tm {
    int tm_sec;         /* seconds */
    int tm_min;         /* minutes */
    int tm_hour;        /* hours */
    int tm_mday;        /* day of the month */
    int tm_mon;         /* month */
    int tm_year;        /* year */
    int tm_wday;        /* day of the week */
    int tm_yday;        /* day in the year */
    int tm_isdst;       /* daylight saving time */
};

The strftime() function formats the broken-down time tm according to our format specification, “%d-%b-%Y %H:%M:%S”.

Output of the program:

Current date and time: 25-Aug-2019 21:45:39

The post C Program to Print Current Date and Time appeared first on QnA Plus.

C Program to Calculate the Sum of All Elements in an Array

$
0
0

Here is the C program that prints the sum of all elements in an array.

#include <stdio.h>

int main(){
  
  int arr[] = {23, 45, 1, 34, 56, 76, 74};
  int i = 0, sum = 0;
  int len = sizeof(arr)/sizeof(int);
  
  for(i = 0; i < len; i++) {
    sum += arr[i];
  }
  
  printf("Sum of all elements in the array: %d\n", sum);
  
  return 0;
}

Output of this program:

Sum of all elements in the array: 309

This program is good enough solution. If you are interested, you can see few other solutions in the following sections.

Recursive Version

We can wire a recursive function for the same purpose.

#include <stdio.h>

int sum(int *arr, int n) {
  if (n == 0) return arr[0];
  
  return arr[n] + sum(arr, n-1);
}

int main(){
  
  int arr[] = {23, 45, 1, 34, 56, 76, 74};
  int result = 0;
  
  result = sum(arr, sizeof(arr)/sizeof(int) - 1);
  
  printf("Summ of all elements in the array: %d\n", result);
  
  return 0;
}

Divide and Conquer

We can apply divide and conquer method also.

#include <stdio.h>

int sum(int *arr, int start, int end) {
  int mid;
  
  if (start == end) return arr[start];
  
  mid = (start + end) / 2;
  
  return sum(arr, start, mid) + sum(arr, mid+1, end);
}

int main(){
  
  int arr[] = {23, 45, 1, 34, 56, 76, 74};
  int result = 0;
  
  result = sum(arr, 0, sizeof(arr)/sizeof(int) - 1);
  
  printf("Summ of all elements in the array: %d\n", result);
  
  return 0;
}

The post C Program to Calculate the Sum of All Elements in an Array appeared first on QnA Plus.


Command Line Arguments in C Programming

$
0
0

An application takes inputs in various ways. It can ask for input from user while it is running. It can read something from file or socket. Another way is, we can give inputs in time of starting the application in the form of command line arguments. For example, when we run Linux commands we give several options as command line arguments to application . Here we’ll see how to write a C program that will take command line arguments.

#include <stdio.h>

int main( int argc, char *argv[] )  {
  int i = 0;
  printf("Application name: %s\n\n", argv[0]);
  
  printf("Command line arguments:\n");
  for(i = 1; i < argc; i++) {
    printf("Argument %d: %s\n", i, argv[i]);
  }
  
  return 0;
}

Here the main() function will have two parameters, argc and argv. When the program starts, argc contains the number of arguments passed, including the application name. The other parameter, argv, is an array of string. It holds all the command line arguments. The first element is always the application name.

Here is the output of the above program.

Command Line Arguments Output

The post Command Line Arguments in C Programming appeared first on QnA Plus.

C Program to Check Whether Two Linked Lists are Equal

$
0
0

Here we’ll see how to write a C program to compare two linked lists. First we’ll create three linked lists, first two are equal and third one is different. We’ll compare these linked lists using the check_equal() function.

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

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

int check_equal(struct node *head1, struct node *head2) {
    
    while(head1 != NULL && head2 != NULL) {
	
	    if(head1->val != head2->val) return 0;
	    
	    head1 = head1->next;
	    head2 = head2->next;
	}
	
	if (head1 != NULL) return 0;
    if (head2 != NULL) return 0;
    
    return 1;
}

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;
}

int main()
{
    struct node * head1 = NULL;
    struct node * head2 = NULL;
    struct node * head3 = NULL;
    
    /*Creating the first linked list*/
    insert_front(&head1, 16);
    insert_front(&head1, 83);
    insert_front(&head1, 89);
    insert_front(&head1, 12);
    insert_front(&head1, 67);
    insert_front(&head1, 20);
    
    /*Creating the second linked list*/
    insert_front(&head2, 16);
    insert_front(&head2, 83);
    insert_front(&head2, 89);
    insert_front(&head2, 12);
    insert_front(&head2, 67);
    insert_front(&head2, 20);

    /*Creating the third linked list*/
    insert_front(&head3, 16);
    insert_front(&head3, 83);
    insert_front(&head3, 50);
    insert_front(&head3, 12);
    insert_front(&head3, 67);
    insert_front(&head3, 20);
    
    printf("Linked List 1: ");
    print_list(head1);
    
    printf("Linked List 2: ");
    print_list(head2);
    
    printf("Linked List 3: ");
    print_list(head3);
    
    printf("\nChecking Linked List 1 and Linked List 2...\n");
    if(check_equal(head1, head2)) {
		printf("Linked List 1 and Linked List 2 are equal.\n");
	} else {
		printf("Linked List 1 and Linked List 2 are not equal.\n");
	}
    
    printf("\nChecking Linked List 1 and Linked List 3...\n");
    if(check_equal(head1, head3)) {
		printf("Linked List 1 and Linked List 3 are equal.\n");
	} else {
		printf("Linked List 1 and Linked List 3 are not equal.\n");
	}
	
    return 0;
}

The check_equal() function traverses the linked lists until at least one of them reaches to NULL (end). If the value fields of two linked list are not equal at any point, the function returns 0 (not equal).

After traversal, if any one list does not reach to NULL (end), then it also returns 0. Next two lines check that. If both lists reach to NULL after traversal and values of all nodes are equal, it returns 1 (equal).

Here is the output of the program.

check two linked list equal

Recursive Version

Here is the recursive function of the check_equal() function.

int check_equal(struct node *head1, struct node *head2) {
    
    if (head1 == NULL && head2 == NULL) return 1;
    
    if(head1 != NULL && head2 != NULL) {
	    if(head1->val != head2->val) return 0;
	    
	    return check_equal(head1->next, head2->next);
	}
    
    return 0;
}

The post C Program to Check Whether Two Linked Lists are Equal appeared first on QnA Plus.

C Program to Print the Length of a Linked List

$
0
0

Here we’ll see how to write a C program to print the length of a linked list. The function get_length() takes a linked list as input and returns the length of it. First we’ll create a linked list and pass that list to the get_length() function to print the length of the list.

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

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

int get_length(struct node *head) {
    int len = 0;
    
    while(head) {
	  len++;
	  head = head->next;
	}
	
	return len;
}

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;
}

int main()
{
    struct node * head = NULL;
    
    /*Creating the linked list*/
    insert_front(&head, 16);
    insert_front(&head, 83);
    insert_front(&head, 89);
    insert_front(&head, 12);
    insert_front(&head, 67);
    insert_front(&head, 20);
    insert_front(&head, 2);
    
    
    printf("Linked List: ");
    print_list(head);
    
    printf("Length of the Linked List: %d.\n", get_length(head));
    
    return 0;
}

The get_length() function traverses the list until it reaches to NULL (end). For every node it increments the variable len and finally returns that.

Here is the output of the above program.

Linked List: H->2->20->67->12->89->83->16->|||

Length of the Linked List: 7.

The post C Program to Print the Length of a Linked List appeared first on QnA Plus.

C Program to Search for an Element in Linked List

$
0
0

Here we’ll see how to write a C program to find an element in a linked list. The function is_present() takes a linked list (head pointer) and a value (val). If the value is present in any of the nodes, this function returns the pointer of that node. Otherwise it returns NULL.

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

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

struct node *is_present(struct node *head, int val) {
    while(head) {
	  if(head->val == val) return head;
	  head = head->next;
	}
	
	return NULL;
}

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;
}

int main()
{
    struct node * head = NULL;
    
    /*Creating the linked list*/
    insert_front(&head, 16);
    insert_front(&head, 83);
    insert_front(&head, 89);
    insert_front(&head, 12);
    insert_front(&head, 67);
    insert_front(&head, 20);
    insert_front(&head, 2);
    
    
    printf("Linked List: ");
    print_list(head);
    
    printf("Finding 99 in the Linked List.\n");
    
    if(is_present(head, 99)) {
		printf("99 is present in the Linked List...\n");
	} else {
		printf("99 is not present in the Linked List.\n");
	}
	
	printf("\nFinding 12 in the Linked List...\n");
    
    if(is_present(head, 12)) {
		printf("12 is present in the Linked List.\n");
	} else {
		printf("12 is not present in the Linked List.\n");
	}
    
    return 0;
}

Here is the output of this program.

Search for an element in a linked list

The post C Program to Search for an Element in Linked List appeared first on QnA Plus.

C Program to Find the Sum of all Digits of a Number

$
0
0

Here we’ll see how to write a C program to find the summation of all digits in a number.

#include <stdio.h>

int sum_digits(int n) {
    int sum = 0;
    while(n) {
	    sum += (n % 10);
	    n /= 10;
	}
	return sum;
}

int main()
{
	int n = 0;
    printf("Enter an integer: ");
    scanf("%d", &n);
    
    printf("Sum of all digits of %d is %d.\n", n, sum_digits(n));
    return 0;
}

The sum_digits() function returns summation of all digits on the input number n. It has a loop. In every iteration it gets the last digit by doing modulo operation by 10 (n%10) and adds that digit to sum. It removes the last digit by doing the div operation by 10. (n/10). The loop terminates when n becomes 0.

Here is the output of the program.

Enter an integer: 43652
Sum of all digits of 43652 is 20.

Recursive Version

Here is the recursive version of the same sum_digits() function.

int sum_digits(int n) {
    int rem = n%10;
    
    if(rem == 0) return n;
    return rem + sum_digits(n/10);
}

The post C Program to Find the Sum of all Digits of a Number appeared first on QnA Plus.

Viewing all 93 articles
Browse latest View live