Author: admin

  • C Program for implementation of Selection sort

    In this tutorial, we will learn and write a C program to implement selection sort using function. Before that you may go through the following topics in C:

    Selection Sort Algorithm

    The selection sort is a simple sorting algorithm which is an in-place comparison-based algorithm. It has two parts where the left end has a sorted part and the right end has an unsorted part.

    In the beginning, the left end is empty and the right end has all the elements then the smallest element from the right end is brought to the left end and swapped with the leftmost element. This process continues until the element from the right end is brought to the left by swapping.

    Although, it may cause a problem with the large inputs.


    Implementation of Selection sort in C

    Question: Selection sort program in C using function.

    // implementation of selection sort in C program
    #include <stdio.h>
    
    void selectionSort(int arr[], int n)
    {
      int i, j, min, temp;
    
      for (i = 0; i < n - 1; i++)
      {
        // finding the minimum
        min = i;
        for (j = i + 1; j < n; j++)
          if (arr[j] < arr[min])
            min = j;
    
        // Swapping
        temp = arr[min];
        arr[min] = arr[i];
        arr[i] = temp;
      }
    }
    
    int main()
    {
      int arr[30], n, i;
    
      printf("Enter the number of elements: ");
      scanf("%d", &n);
    
      printf("Enter %d Elements:\n", n);
      for (i = 0; i < n; i++)
      {
        scanf("%d", &arr[i]);
      }
    
      //calling sorting function
      selectionSort(arr, n);
    
      //Display the result
      printf("\nArray after sorting: \n");
      for (i = 0; i < n; i++)
        printf("%d ", arr[i]);
    
      return 0;
    }

    Output:

    Enter the number of elements: 6
    Enter 6 Elements:
    25
    12
    88
    5
    76
    50

    Array after sorting:
    5 12 25 50 76 88

    Time Complexity of Selection Sort:

    • Best case:  0(n^2)
    • Average case:  0(n^2)
    • Worst case:  0(n^2)

  • C Program to Delete a Particular element from an Array

    In this tutorial, we will write a C program to delete an element in an array by specifying the value. Before that, you should have knowledge on the following C topics:

    Example:

    Input
    Input array elements: 11 22 30 42 50
    Specify the value to delete: 22

    Output
    Array elements: 11 30 42 50

    Explanation: Here instead of a position of an element, the value of the element is specified to delete. Similarly, the program traverse until the element is found and then shifts all the elements from index + 1 by 1 position to the left.

    And if the value is not that is the entered value does not match with any element present in an array, in that case, the program will display the message “Element Not Valid”.


    C Program to Delete a Particular element from an Array

    #include <stdio.h>
    
    int main()
    {
       int arr[50], element, i, size, pos;
       int element_found = 0;
    
       printf("Enter the size of an array: ");
       scanf("%d", &size);
    
       printf("Enter %d elements\n", size);
    
       for (i = 0; i < size; i++)
          scanf("%d", &arr[i]);
    
       printf("\nArray before Deletion:\n");
       for (i = 0; i < size; i++)
          printf("%d ", arr[i]);
    
       printf("\n\nEnter the element to be deleted: ");
       scanf("%d", &element);
    
       // check the element to be deleted is in array or not
       for (i = 0; i < size; i++)
       {
          if (arr[i] == element)
          {
             element_found = 1;
             pos = i;
             break;	// terminate the loop
          }
       }
    
       if (element_found == 1)  // for element exists
       {
          for (i = pos; i < size - 1; i++)
             arr[i] = arr[i + 1];
       }
       else	//for element does not exists
          printf("\nElement %d is not present in an Array. Try Again!", element);
    
       printf("\nArray after Deletion:\n");
       for (i = 0; i < size - 1; i++)
          printf("%d  ", arr[i]);
    
       return 0;
    }

    Output:

    Enter the size of an array: 5
    Enter 5 elements
    10
    20
    30
    40
    50
    
    Array before Deletion:
    10 20 30 40 50 
    
    Enter the element to be deleted: 30
    
    Array after Deletion:
    10 20 40 50

  • C Program to sort a String in Ascending order

    In this tutorial, we will write a c program to sort a string array in ascending order. Before that, you may go through the following topics in C


    C Program to sort a String in Ascending order

    #include <stdio.h>
    #include <string.h>
    #define MAX_size 100	//maxiimum size of the string
    
    void main()
    {
      char str[MAX_size], ch;
      int i, j, length;
    
      printf("Enter the string: ");
      fgets(str, sizeof str, stdin);
    
      length = strlen(str);
    
      for (i = 1; i < length; i++)
      {
        for (j = 0; j < length - i; j++)
        {
          if (str[j] > str[j + 1])
          {
            ch = str[j];
            str[j] = str[j + 1];
            str[j + 1] = ch;
          }
        }
      }
    
      printf("\nAfter sorting, the string appears: %s", str);
    }

    Output:

    Enter the string: programs

    After sorting, the string appears:
    agmoprrs


  • C Program to find Maximum occurring Character in a String

    In this tutorial, we will write a program in C to find the maximum occurring character in a string. Before that, you may go through the following topics in C


    Find maximum occurring character in a string in C

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    #define MAX_size 100	//MAX string size
    #define MAX_char 255	//MAX character number
    
    void main()
    {
      char str[MAX_size];
      int freq[MAX_char];
      int i = 0, max;
      int ascii;
    
      printf("Enter the string : ");
      fgets(str, sizeof str, stdin);
    
      for (i = 0; i < MAX_char; i++)
      {
        freq[i] = 0;
      }
    
      //calculating the frequency
      i = 0;
      while (str[i] != '\0')
      {
        ascii = (int) str[i];
        freq[ascii] += 1;
    
        i++;
      }
    
      max = 0;
      for (i = 0; i < MAX_char; i++)
      {
        if (i != 32)
        {
          if (freq[i] > freq[max])
            max = i;
        }
      }
    
      printf("\nCharacter with highest frequency is: '%c'", max);
      printf("\nAnd the number of times, it appears is: '%d'", freq[max]);
    }

    Output:

    Enter the string : Welcome to simple2code

    Character with highest frequency is: 'e'
    And the number of times, it appears is: '4'


  • Keith Number Program in C

    In this tutorial, we will write a Keith number in C. It is one of the most asked questions in an interview. Before that, you may go through the following topic in C programming.

    What is Keith Number?

    A positive n digit number x is called a Keith number or repfigit number (repetitive Fibonacci-like digit) if it is arranged in a special number sequence generated using its digits. This sequence has n terms as digit of x and the next term is determined by the sum of previous n terms and so on. And if the number x falls under this sequence then x is a Keith Number. Example: 19, 742, etc

    Explanation: Consider the number 742. Go through the following steps:

    First separate the digit, 7, 4, 2.

    To find the next term, add the digits, 7+4+2 = 13
    New Series: 7, 4, 2, 13.

    To find the next term, add the last three digits of the above sequence, 13+2+4=19
    New Series: 7, 4, 2, 13, 19.

    To find the next term, add the last three digits of the above sequence, 19+13+2=34
    New Series: 7, 4, 2, 13, 19, 34.

    To find the next term, add the last three digits of the above sequence, 34+19+13=66
    New Series: 7, 4, 2, 13, 19, 34, 66.

    To find the next term, add the last three digits of the above sequence, 66+34+19=119
    New Series: 7, 4, 2, 13, 19, 34, 66, 119.

    To find the next term, add the last three digits of the above sequence, 119+66+34=219
    New Series: 7, 4, 2, 13, 19, 34, 66, 119, 219.

    To find the next term, add the last three digits of the above sequence, 219+119+66=404
    New Series: 7, 4, 2, 13, 19, 34, 66, 119, 219, 404.

    To find the next term, add the last three digits of the above sequence, 404+219+119=742
    New Series: 7, 4, 2, 13, 19, 34, 66, 119, 219, 404, 742.

    Now we will stop as we got the number 742 as the term of the series. Hence 742 is a Keith Number.


    C Program to check whether the Number is Keith Number or not

    #
    include < stdio.h > 
    #include <stdlib.h >
    
    //user defined funtion to count the length
    int digitCount(int n)
    {
      int counter = 0;
      while (n > 0)
      {
        n = n / 10;
        counter++;
      }
    
      return counter;
    }
    
    int main()
    {
      int num1 = 0, arr1[10], temp = 0, flag = 0, i = 0, sum = 0;
    
      printf("Enter a number: ");
      scanf("%d", &num1);
    
      temp = num1;
    
      for (i = digitCount(temp) - 1; i >= 0; i--)
      {
        arr1[i] = num1 % 10;
        num1 /= 10;
      }
    
      while (flag == 0)
      {
        for (i = 0; i < digitCount(temp); i++)
          sum += arr1[i];
        if (sum == temp)
        {
          printf("The entered number is a Keith Number\n");
          flag = 1;
        }
    
        if (sum > temp)
        {
          printf("The entered number is NOT a Keith number\n");
          flag = 1;
        }
    
        for (i = 0; i < digitCount(temp); i++)
        {
          if (i != digitCount(temp) - 1)
            arr1[i] = arr1[i + 1];
          else
            arr1[i] = sum;
        }
    
        sum = 0;
      }
    }

    Output:

    //Run 1
    Enter a number: 197
    The entered number is a Keith Number

    //Run 2
    Enter a number: 15
    The entered number is NOT a Keith number


  • Keith Number Program in C++

    In this tutorial, we will write a Keith number in C++. It is one of the most asked questions in an interview. Before that, you may go through the following topic in C programming.

    What is Keith Number?

    A positive n digit number x is called a Keith number or repfigit number (repetitive Fibonacci-like digit) if it is arranged in a special number sequence generated using its digits. This sequence has n terms as digit of x and the next term is determined by the sum of previous n terms and so on. And if the number x falls under this sequence then x is a Keith Number. Example: 19, 742, etc

    Explanation: Consider the number 742. Go through the following steps:

    First separate the digit, 7, 4, 2.

    To find the next term, add the digits, 7+4+2 = 13
    New Series: 7, 4, 2, 13.

    To find the next term, add the last three digits of the above sequence, 13+2+4=19
    New Series: 7, 4, 2, 13, 19.

    To find the next term, add the last three digits of the above sequence, 19+13+2=34
    New Series: 7, 4, 2, 13, 19, 34.

    To find the next term, add the last three digits of the above sequence, 34+19+13=66
    New Series: 7, 4, 2, 13, 19, 34, 66.

    To find the next term, add the last three digits of the above sequence, 66+34+19=119
    New Series: 7, 4, 2, 13, 19, 34, 66, 119.

    To find the next term, add the last three digits of the above sequence, 119+66+34=219
    New Series: 7, 4, 2, 13, 19, 34, 66, 119, 219.

    To find the next term, add the last three digits of the above sequence, 219+119+66=404
    New Series: 7, 4, 2, 13, 19, 34, 66, 119, 219, 404.

    To find the next term, add the last three digits of the above sequence, 404+219+119=742
    New Series: 7, 4, 2, 13, 19, 34, 66, 119, 219, 404, 742.

    Now we will stop as we got the number 742 as the term of the series. Hence 742 is a Keith Number.


    C++ Program to check whether the Number is Keith Number or not

    #include <bits/stdc++.h>
    using namespace std;
    
    int digitCount(int n)
    {
      int counter = 0;
      while (n > 0)
      {
        n = n / 10;
        counter++;
      }
    
      return counter;
    }
    
    int main()
    {
      int num1 = 0, arr1[10], temp = 0, flag = 0, i = 0, sum = 0;
    
      cout << "Enter a number: ";
      cin >> num1;
    
      temp = num1;
    
      for (i = digitCount(temp) - 1; i >= 0; i--)
      {
        arr1[i] = num1 % 10;
        num1 /= 10;
      }
    
      while (flag == 0)
      {
        for (i = 0; i < digitCount(temp); i++)
          sum += arr1[i];
        if (sum == temp)
        {
          cout << "The entered number is a Keith Number\n";
          flag = 1;
        }
    
        if (sum > temp)
        {
          cout << "The entered number is NOT a Keith Number\n";
          flag = 1;
        }
    
        for (i = 0; i < digitCount(temp); i++)
        {
          if (i != digitCount(temp) - 1)
            arr1[i] = arr1[i + 1];
          else
            arr1[i] = sum;
        }
    
        sum = 0;
      }
    }

    Output:

    //Run 1
    Enter a number: 197
    The entered number is a Keith Number

    //Run 2
    Enter a number: 15
    The entered number is NOT a Keith number


  • Singly linked list Program C++

    In this tutorial, we will write a C++ program to implement singly linked list.

    In this program, we will create a separate function for each operation that is to be performed in a linked list. This operation includes:

    • create()
    • insert(): this includes insetion at the begining, at the end or at a given position.
    • delet() : delete is also the same that is at the begining, at the end or at a given position.
    • display()
    • search()

    The program takes user input at every step necessary from the user and performed accordingly. The following are the various C++ programming topics used in the program.

    Singly linked list in C++

    #include <iostream>
    #include <conio.h>
    #include <stdlib.h>
    using namespace std;
    
    class Node
    {
      public_colon
      int info;
      Node * next;
    };
    
    class List: public Node
    {
    
      Node *first, *last;
      public_colon
      List()
      {
        first = NULL;
        last = NULL;
      }
      void create();
      void insert();
      void delet();
      void display();
      void search();
    };
    
    //create function
    void List::create()
    {
      Node * temp;
      temp = new Node;
      int n;
    
      cout << "\nEnter an Element: ";
      cin >> n;
    
      temp->info = n;
      temp->next = NULL;
      if (first == NULL)
      {
        first = temp;
        last = first;
      }
      else
      {
        last->next = temp;
        last = temp;
      }
    }
    
    //insert function
    //at chosen position
    void List::insert()
    {
      Node *prev, *cur;
      prev = NULL;
      cur = first;
      int count = 1, pos, ch, n;
      Node *temp = new Node;
    
      cout << "\nEnter an Element: ";
      cin >> n;
    
      temp->info = n;
      temp->next = NULL;
      cout << "\nChoose the position:";
      cout << "\n1 for the beginning.";
      cout << "\n2 for the end.";
      cout << "\n3 for in between.";
      cout << "\nEnter Your Choice: ";
      cin >> ch;
    
      switch (ch)
      {
        case 1:
          temp->next = first;
          first = temp;
          break;
        case 2:
          last->next = temp;
          last = temp;
          break;
        case 3:
          cout << "\nEnter the Position to Insert: ";
          cin >> pos;
          while (count != pos)
          {
            prev = cur;
            cur = cur->next;
            count++;
          }
          if (count == pos)
          {
            prev->next = temp;
            temp->next = cur;
          }
          else
            cout << "\nNot Able to Insert";
          break;
      }
    }
    
    //function to delete
    //at chosen position
    void List::delet()
    {
      Node *prev = NULL, *cur = first;
      int count = 1, pos, ch;
      cout << "Select the position for deletion: \n";
      cout << "\n1 for the beginning.";
      cout << "\n2 for the end.";
      cout << "\n3 for in between.";
      cout << "\nEnter Your Choice:";
      cin >> ch;
    
      switch (ch)
      {
        case 1:
          if (first != NULL)
          {
            cout << "\nDeleted Element is " << first->info;
            first = first->next;
          }
          else
            cout << "\nOperation Failed";
          break;
        case 2:
          while (cur != last)
          {
            prev = cur;
            cur = cur->next;
          }
          if (cur == last)
          {
            cout << "\nDeleted Element is: " << cur->info;
            prev->next = NULL;
            last = prev;
          }
          else
            cout << "\nOperation Failed";
          break;
        case 3:
          cout << "\nEnter the Position of Deletion: ";
          cin >> pos;
          while (count != pos)
          {
            prev = cur;
            cur = cur->next;
            count++;
          }
    
          if (count == pos)
          {
            cout << "\nDeleted Element is: " << cur->info;
            prev->next = cur->next;
          }
          else
          {
            cout << "\nOperation Failed";
          }
          break;
      }
    }
    
    //display function
    //check for empty list first
    void List::display()
    {
      Node *temp = first;
      if (temp == NULL)
      {
        cout << "\nList is Empty";
      }
      while (temp != NULL)
      {
        cout << temp->info;
        cout << "-->";
        temp = temp->next;
      }
      cout << "NULL";
    }
    
    //search function
    //check for empty list first
    void List::search()
    {
      int value, pos = 0;
      bool flag = false;
    
      if (first == NULL)
      {
        cout << "List is Empty";
        return;
      }
      cout << "Enter the Value to be Searched: ";
      cin >> value;
    
      Node * temp;
      temp = first;
      while (temp != NULL)
      {
        pos++;
        if (temp->info == value)
        {
          flag = true;
          cout << "Element" << value << "is Found at " << pos << " Position";
          return;
        }
        temp = temp->next;
      }
      if (!flag)
      {
        cout << value << " is not present in the List";
      }
    }
    
    //drive function
    int main()
    {
      List ls;
      int ch;
      while (1)
      {
        cout << "\nChoose an Operation: ";
        cout << "\n1 to CREATE.";
        cout << "\n2 to INSERT.";
        cout << "\n3 to DELETE.";
        cout << "\n4 to SEARCH.";
        cout << "\n5 to DISPLAY.";
        cout << "\n6 to EXIT.";
        cout << "\nEnter Your Choice: ";
        cin >> ch;
    
        switch (ch)
        {
          case 1:
            ls.create();
            break;
          case 2:
            ls.insert();
            break;
          case 3:
            ls.delet();
            break;
          case 4:
            ls.search();
            break;
          case 5:
            ls.display();
            break;
          case 6:
            return 0;
        }
      }
      return 0;
    }

    Output:

    Choose an Operation:
    1 to CREATE.
    2 to INSERT.
    3 to DELETE.
    4 to SEARCH.
    5 to DISPLAY.
    6 to EXIT.
    Enter Your Choice: 1

    Enter an Element: 2

    Choose an Operation:
    1 to CREATE.
    2 to INSERT.
    3 to DELETE.
    4 to SEARCH.
    5 to DISPLAY.
    6 to EXIT.
    Enter Your Choice: 2

    Enter an Element: 4

    Choose the position:
    1 for the beginning.
    2 for the end.
    3 for in between.
    Enter Your Choice: 2

    Choose an Operation:
    1 to CREATE.
    2 to INSERT.
    3 to DELETE.
    4 to SEARCH.
    5 to DISPLAY.
    6 to EXIT.
    Enter Your Choice: 5
    2-->4-->NULL
    Choose an Operation:
    1 to CREATE.
    2 to INSERT.
    3 to DELETE.
    4 to SEARCH.
    5 to DISPLAY.
    6 to EXIT.
    Enter Your Choice: 6

    Similarly, you can follow the option, and then you can search and delete an element from the list.


  • Fascinating Number Program in C

    In this tutorial, we will write a C program to check whether the given number is a Fascinating number or not. You may go through the following topics first in C.

    What is Fascinating Number?

    A number is said to be a fascinating number if it is (having at least 3 digits) multiplied by 2 and 3, and then both these product’s results are concatenated with the original number, then the new number contains all the digits from 1 to 9 exactly once. There could be any number of zeros and are ignored.

    Fascinating number example:

    Consider a Number = 192
    Then multiply it by two and 3
    192 × 2 = 384
    192 × 3 = 576
    Concatenating the above two numbers with the original number, we get:
    “192” + “384” + “576” = 192384576 = result.
    Now the final result contains all the digits from 1 to 9. Hence it is a Fascinating Number.


    Procedure for Fascinating Number

    1. First, check if the entered/given number has three digits or not. If not, print “cannot be a Fascinating Number”.
    2. Else, Multiply the given number with 2 and 3.
    3. Then convert the product result into a string and Concatenate those strings along with the original number.
    4. Iterate the string that we get after concatenation and also keep the frequency count of the digits.
    5. Print “Not a Fascinating Number” if any of the digits (1 to 9) is missing or repeated.
    6. Else, print “It is a Fascinating Number”.

    C Program for Fascinating Number

    #include <stdio.h>
    #include <stdbool.h>
    #include <math.h>
    
    //function
    int countDigits(int n)
    {
      int count = 0;
      while (n > 0)
      {
        count++;
        n /= 10;
      }
    
      return count;
    }
    
    int main(void)
    {
      int num;
    
      printf("Enter a number: ");
      scanf("%d", &num);
    
      //calculating the product
      int product2 = num * 2;
      int product3 = num * 3;
    
      //Concatinating all three
      int concatNum = 0;
      concatNum += num;
      concatNum = concatNum* pow(10, countDigits(product2)) + product2;
      concatNum = concatNum* pow(10, countDigits(product3)) + product3;
    
      //Count the occurence
      int count[10] = { 0 };
      while (concatNum > 0)
      {
        count[concatNum % 10]++;
        concatNum = concatNum / 10;
      }
    
      //Check for 1
      bool isFound = true;
      for (int i = 1; i < 10; i++)
      {
        if (count[i] != 1)
        {
          isFound = false;
          break;
        }
      }
    
      //Display the result
      if (isFound)
        printf("%d is a Fascinating number.", num);
      else
        printf("%d is NOT a Fascinating number.", num);
    
      return 0;
    }

    Output:

    Enter a number: 192
    192 is a Fascinating number.


  • Peterson Number in C

    In this tutorial, we will learn about the Peterson number and check if the number is Peterson or not in C.

    What is Peterson Number?

    A number is said to be a Peterson number if the sum of factorials of each digit of the number is equal to the number itself.

    Peterson numbers examples:

    Number = 145
    145 = !1 + !4 + !5
    = 1 + 4*3*2*1 + 5*4*3*2*1
    = 1 + 24 + 120
    = 145 = 145

    Therefore, we can see that after the sum of the factorial of 145 is equal to the number 145 itself. Hence the Peterson Number.


    C Program to check whether the number is Peterson Number or not

    Peterson number program in C:

    #include <stdio.h>
    
    int main()
    {
      int num, temp, rem, sum = 0, fact = 1;
      int i;
    
      printf("Enter a number: ");
      scanf("%d", &num);
    
      temp = num;
      while (temp != 0)
      {
        rem = temp % 10;
        for (i = 1; i <= rem; i++)
          fact *= i;
    
        sum += fact;
        fact = 1;
        temp /= 10;
      }
    
      //display
      if (num == sum)
        printf("%d is a Peterson Number", num);
      else
        printf("%d is Not a Peterson Number", num);
    
      return 0;
    }

    Output 1:

    Enter a number: 145
    145 is a Peterson number

    Output 2:

    Enter a number: 55
    55 is not a Peterson number


  • Peterson Number in C++

    In this tutorial, we will learn about the Peterson number and write a C++ program to check if the given number is a Peterson number or not.

    What is Peterson Number?

    A number is said to be a Peterson number if the sum of factorials of each digit of the number is equal to the number itself.

    Peterson numbers example:

    Number = 145
    145 = !1 + !4 + !5
    = 1 + 4*3*2*1 + 5*4*3*2*1
    = 1 + 24 + 120
    = 145 = 145

    Therefore, we can see that after the sum of the factorial of 145 is equal to the number 145 itself. Hence the Peterson Number.


    Cpp program to check a number is Peterson number or not

    #include <iostream>
    using namespace std;
    
    int peterson_func(int num)
    {
      int rem, sum = 0, fact = 1, i;
    
      while (num != 0)
      {
        rem = num % 10;
    
        for (i = 1; i <= rem; i++)
          fact *= i;
    
        sum += fact;
        fact = 1;
        num /= 10;
    
      }
    
      return sum;
    }
    
    int main()
    {
      int num, sum = 0, temp;
    
      cout << "Enter a number: ";
      cin >> num;
    
      temp = num;
      sum = peterson_func(num);
    
      if (sum == temp)
        cout << num << " is a Peterson number";
      else
        cout << num << " is NOT a Peterson number";
    
      return 0;
    }

    Output:

    Enter a number: 145
    145 is a Peterson number

    Enter a number: 55
    55 is not a Peterson number