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

Count Set Bits of a Number in C

$
0
0

A number consists of multiple bits in its binary representation. For example, an integer would have 32 bits and a long would have 64 bits on 64-bit system. Bit values could either be 0 (not set) or 1 (set).

Set Bits of a Number

From the diagram above, we can see that the binary representation of 2392 has 5 set bits.

Here we’ll see how to write C program to count the set bits of a number.

Checking All Bits

We can check all bits of a number in a loop and increment the counter if the a particular bit is 1 (set).

Logic

  1. If the bitwise AND (&) operation between the number and 1 is 1, then increment the set bit count.
  2. Right shift the number by 1, and repeat step 1 as the many times as the size of the number in bits.

The Program

#include <stdio.h>

int count_set_bits(unsigned int n) {
  int size, count = 0;
  
  size = sizeof(unsigned int) * 8;
  
  while(size--) {
    count += n & 0x01;
    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 first takes an integer as input and prints its binary representation. It calls the count_set_bits() function to count the set bits in the number and print that.

Here is the output.

Count Bits Output

Recursive version

We can write this count_set_bits() as a recursive function.

  1. If the input number n is 0, return 0. There is no set bits.
  2. Get the set bit counts of (n >> 1) calling the same function recursively. The result would be the returned value plus 1 if the least significant bit of the input is 1, i.e. (n & 0x01) is 1.
int count_set_bits(unsigned int n) {
  
  if (n == 0) return 0;
  
  return count_set_bits(n >> 1) + (n & 0x01);
}

Using Brian Kernighan’s Algorithm

In the previous section’s solution we iterated as many times as the number of bits in the number. But if we apply Brian Kernighan’s algorithm, we can get the result with less number of iterations.

In this article, I discussion about the Brian Kernighan’s algorithm in detail. Here we’ll see the count_set_bits() function’s implementation.

Non-recursive Version

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

Recursive Version

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 Count Set Bits of a Number in C appeared first on QnA Plus.


Add New Node to XML File Using libxml2 in C

$
0
0

In the previous article, we saw how to parse an XML file. Here we’ll see how to add new node to XML file using C programming language. Here also we’ll use libxml2 parser.

We’ll use this XML file as an example.

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

Here we have 3 book nodes under the catalog node. We’ll add one more book node.

C Program to Add New Node to XML File

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

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

xmlNode * find_node(xmlNode * node, char * name) {
  
  if (node == NULL) return NULL;
  
  while(node) {
    if((node->type == XML_ELEMENT_NODE) && (strcmp(node->name, name) == 0)) {
      return node;
        
      find_node(node->children, name);
      node = node->next;
    }
  }
}

void add_node(xmlNode *root, char* id, char* author, char* title) {
  xmlNode* node = find_node(root, "catalog");
  xmlNode* new_node = NULL;
  xmlNode* new_child_node = NULL;
  
  if(node == NULL) return;
  new_node = xmlNewNode(NULL, BAD_CAST "book");
  xmlSetProp(new_node, "id", id);
  
  new_child_node = xmlNewNode(NULL, BAD_CAST "author");
  xmlNodeSetContent(new_child_node, author);
  xmlAddChild(new_node, new_child_node);
  
  new_child_node = xmlNewNode(NULL, BAD_CAST "title");
  xmlNodeSetContent(new_child_node, title);
  xmlAddChild(new_node, new_child_node);
  
  xmlAddChild(node, new_node);
}

void save_to_file(xmlDoc *doc, char *file_name) {
  xmlChar *xmlbuff;
  int buffersize;
  FILE *fp;
  
  xmlDocDumpFormatMemory(doc, &xmlbuff, &buffersize, 1);
  
  fp = fopen(file_name, "w+");
  fprintf(fp, xmlbuff);
  fclose(fp);
}

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

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

  if (doc == NULL) {
    printf("Could not parse the XML file.\n");
    return 1;
  }

  root_element = xmlDocGetRootElement(doc);

  add_node(root_element, "bk500", "F. Scott Fitzgerald", "The Great Gatsby");
  
  save_to_file(doc, "output.xml");
  
  xmlFreeDoc(doc);

  xmlCleanupParser();
  
  return 0;
}

This program reads the “input.xml” file and adds a new book node. Then it saves the content to “output.xml“. We could overwrite the “input.xml” also. Lets have a look at the various functions of this program.

find_node(): It can find any node in the XML file based on a node name. If found, then it returns the node pointer. We used this function to find the ‘catalog‘ node.

add_node(): This function adds new book node under ‘catalog‘. It first finds the ‘catalog‘ node by calling find_node() function. Then it creates the ‘book‘ and adds the ‘id‘ property. This shows how to add a property of attribute to an XML node. The two child nodes, ‘ author‘ and ‘title‘, are created and added to the ‘book‘ node. We set content to ‘author‘ and ‘title‘ nodes. Finally the ‘book‘ node is added under ‘catalog‘.

save_to_file(): This function saves the XML content to a file.

The main() function first reads the ‘input.xml‘ file and calls the add_node() function with required information to add a ‘book‘ node. Then it calls the save_to_file() function to save the modified XML content to ‘output.xml‘ file.

If you don’t have libxml2 development library installed on your system, then you have to install that first to compile the program.

To compile this program, run this command.

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

The ‘input.xml‘ file needs to be present in the same directory in time of running the program.

The ‘output.xml’ file would be generated in the same directory. If we open the file, we can see the new book entry..

Add new node to XML file

The post Add New Node to XML File Using libxml2 in C appeared first on QnA Plus.

Delete an XML Node using libxml2 in C

$
0
0

In the previous article we saw how to add a new XML node. Here we’ll see how to delete an an XML node from a file. We’ll use the same example XML file.

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

In this example, we have 3 ‘book‘ nodes under ‘catalog‘. We’ll write a C program to delete one of them.

Program to Delete XML Node

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

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

xmlNode * find_node(xmlNode * node, char * book_id) {
  
  xmlNode * result;
  
  if (node == NULL) return NULL;
  
  while(node) {
    if((node->type == XML_ELEMENT_NODE) 
        && (strcmp(node->name, "book") == 0)
        && (strcmp(xmlGetProp(node, "id"), book_id) == 0)) {
      return node;
    }
    
    if (result = find_node(node->children, book_id)) return result;
    
    node = node->next;
  }
  
  return NULL;
}

void delete_node(xmlNode *root, char* book_id) {
  xmlNode* node = find_node(root, book_id);
  
  if(node == NULL) {
    printf("Book with id %s not found\n", book_id);
    return;
  }
  
  xmlUnlinkNode(node);
  xmlFreeNode(node);
}

void save_to_file(xmlDoc *doc, char *file_name) {
  xmlChar *xmlbuff;
  int buffersize;
  FILE *fp;
  
  xmlDocDumpFormatMemory(doc, &xmlbuff, &buffersize, 1);
  
  fp = fopen(file_name, "w+");
  fprintf(fp, xmlbuff);
  fclose(fp);
}

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

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

  if (doc == NULL) {
    printf("Could not parse the XML file.\n");
    return 1;
  }

  root_element = xmlDocGetRootElement(doc);

  delete_node(root_element, "bk102");
  
  save_to_file(doc, "output.xml");
  
  xmlFreeDoc(doc);

  xmlCleanupParser();
  
  return 0;
}

This program has the following important functions.

find_node(): It finds a ‘book‘ node based on a book id. It traverses the XML doc and returns a node whose node name is ‘book‘ and the ‘id‘ property of that node is equal to the input book id.

delete_node(): It takes a book id as input and deletes the book node with this book id. It first finds the node by calling the find_node() function. Then it detaches that node from the XML doc by calling xmlUnlinkNode() function. After that it frees the detached node using xmlFreeNode() to void memory leak.

save_to_file(): Saves the XML doc into a file.

In the main() function, we first read the “input.xml” file. So this ‘input.xml‘ files needs to be present in time of running the program in the same directory. Then we called the delete_node() function to delete the second book entry. That’s why we passed ‘bk102book id as input. After deleting the node, we saved the XML content to ‘output.xml‘ file.

To compile this program, run this command.

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

It requires libxml2 development package. If it is not already installed, then you can follow this article to install that first.

If you run this program (./test), the ‘output.txt‘ will get generated in the same directory. The ‘output.txt‘ will not have the second book entry.

Delete an xml node output

The post Delete an XML Node using libxml2 in C appeared first on QnA Plus.

Search for an XML Node using libxml2 in C

$
0
0

XML is widely used format to store or transmit data over internet. Here we’ll see how to search for an XML node in a file. We’ll use this XML file as an example.

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

Search XML Node by its Name

First we’ll see how to search a node based on its name. In the above example XML file, node names are ‘catalog‘, ‘book‘, ‘author‘ etc.

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

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

xmlNode * find_node(xmlNode * node, char * node_name) {
  
  xmlNode * result;
  
  if (node == NULL) return NULL;
  
  while(node) {
    if((node->type == XML_ELEMENT_NODE) 
        && (strcmp(node->name, node_name) == 0)) {
      return node;
    }
    
    if (result = find_node(node->children, node_name)) return result;
    
    node = node->next;
  }
  
  return NULL;
}

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

  char node_name[256];

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

  if (doc == NULL) {
    printf("Could not parse the XML file.\n");
    return 1;
  }

  printf("Node to search: ");
  scanf("%s", node_name);
  
  root_element = xmlDocGetRootElement(doc);

  result = find_node(root_element, node_name);
  
  if (result) {
    printf ("Node '%s' is found in the XML.\n", node_name);
  } else {
    printf ("Node '%s' is not found in the XML.\n", node_name);
  }
  
  xmlFreeDoc(doc);
  xmlCleanupParser();
  
  return 0;
}

This program takes a node name as input. Then calls the find_node() function to check whether a node with that name exists. If the find_node() function finds a match, then it returns that node pointer, otherwise, NULL. To compile the code, libxml2 development library is required. If you don’t have it installed, install it first.

To compile the program, run this command.

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

Here is the output of the program.

search xml node by its name

From the output, we can see that searching with node names ‘catalog‘ and ‘book‘ succeeded but failed for node name ‘pen‘.

Search XML Node by its Property Name

In our example XML file, there are three ‘book‘ nodes. If we want to search for a specific ‘book‘ entry, we can search for the ‘id‘ property. The find_node() function will search based on the ‘id‘ property.

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

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

xmlNode * find_node(xmlNode * node, char * prop_val) {
  
  xmlNode * result;
  
  if (node == NULL) return NULL;
  
  while(node) {
    if((node->type == XML_ELEMENT_NODE)
        && xmlGetProp(node, "id")
        && (strcmp(xmlGetProp(node, "id"), prop_val) == 0)) {
      return node;
    }
    
    if (result = find_node(node->children, prop_val)) return result;
    
    node = node->next;
  }
  
  return NULL;
}

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

  char prop_val[256];

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

  if (doc == NULL) {
    printf("Could not parse the XML file.\n");
    return 1;
  }

  printf("Enter id property: ");
  scanf("%s", prop_val);
  
  root_element = xmlDocGetRootElement(doc);

  result = find_node(root_element, prop_val);
  
  if (result) {
    printf ("Node with id '%s' is found in the XML.\n", prop_val);
  } else {
    printf ("Node with id '%s' is not found in the XML.\n", prop_val);
  }
  
  xmlFreeDoc(doc);
  xmlCleanupParser();
  
  return 0;
}

Here is the output of the program.

Search XML node by property value

From the output, we can see that searching for book id ‘bh102‘ was successful. But search for ‘bk100’ failed.

The property name here is ‘id‘ but it could be different in different XML file. We can slightly modify our find_node() function to take the property name as input also.

xmlNode * find_node(xmlNode * node, char * prop_name, char * prop_val) {
  
  xmlNode * result;
  
  if (node == NULL) return NULL;
  
  while(node) {
    if((node->type == XML_ELEMENT_NODE)
        && xmlGetProp(node, prop_name)
        && (strcmp(xmlGetProp(node, prop_name), prop_val) == 0)) {
      return node;
    }
    
    if (result = find_node(node->children, prop_name, prop_val)) return result;
    
    node = node->next;
  }
  
  return NULL;
}

Search XML Node by Content

We can search by a content, which lies between a start node and a end node, also.

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

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

xmlNode * find_node(xmlNode * node, char * content) {
  
  xmlNode * result;
  
  if (node == NULL) return NULL;
  
  while(node) {
    if((node->type == XML_ELEMENT_NODE)
        && (strcmp(xmlNodeGetContent(node), content) == 0)) {
      return node;
    }
    
    if (result = find_node(node->children, content)) return result;
    
    node = node->next;
  }
  
  return NULL;
}

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

  char content[256];

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

  if (doc == NULL) {
    printf("Could not parse the XML file.\n");
    return 1;
  }

  printf("Enter id property: ");
  gets(content);
  
  root_element = xmlDocGetRootElement(doc);

  result = find_node(root_element, content);
  
  if (result) {
    printf ("Node with content '%s' is found in the XML.\n", content);
  } else {
    printf ("Node with content '%s' is not found in the XML.\n", content);
  }
  
  xmlFreeDoc(doc);
  xmlCleanupParser();
  
  return 0;
}

Here is the output.

Search xml node by content

It could find a node with content ‘Gambardella, Matthew‘ but failed for ‘Mark Twain‘.

The post Search for an XML Node using libxml2 in C appeared first on QnA Plus.

Circular Linked List in C

$
0
0

Circular linked list is like a regular linked list except its last node points to the first node. Generally the last node of linked list points to NULL. But the last node of circular linked list points back to the first node.

Circular Linked List

If you traverse a regular linked list, you can not come back to a previous node. You can not traverse back. And you can not go anywhere from the last node. But in circular linked list, you can come back to any previous node as the last node points back to the first node.

We keep a pointer to access the linked list. In regular linked, head points to the first node. But for circular linked list, its better to keep a pointer pointing to the last node.

If we keep a head pointer pointing to the first node, then to insert a new node at the end, we have to traverse the whole list. But for last pointer pointing to the last node, we can insert a new node at the front or at the end without traversing the list.

Circular Linked List Operations

Traverse the Circular Linked List

Normally we traverse a linked list from head to NULL. But in circular linked list, no node points to NULL. So at the beginning we have to save the node where we started traversal. We have to stop we when we came back to the starting node.

/*Print the linked list*/
void print_list(struct node *in_node) {
  struct node *start = in_node;

  do {
    printf("%d->", in_node->val);
    in_node = in_node->next;
  } while (start != in_node);
  
  printf("\n");
}

Insert at the Front

  1. Create the new node (new_node) and set the value of the node (new_node->val = val)
  2. If last is NULL, point last to the new node (last = new_node) and point the new node to itself (new_node->next = new_node).
  3. Else, point the new node where the last node is pointing to (new_node->next = last->next). And point the last node to the new node (last->next = new_node).
Insert at the from of a circular linked list

The Program

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

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

/*Print the linked list*/
void print_list(struct node *in_node) {
  struct node *start = in_node;

  do {
    printf("%d->", in_node->val);
    in_node = in_node->next;
  } while (start != in_node);
  
  printf("\n");
}

/*Insert an element at the front of the list*/
void insert_front(struct node **last, int value) {
  /*Allocating memory for the new node*/
  struct 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;
    
  if(*last == NULL) {
    /*List is empty*/
    *last = new_node;
    new_node->next = new_node;
    return;
  }

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

  /*Pointing last node to new node.*/
  (*last)->next = new_node;
}

void main()
{
  int count = 0, i, val;
  struct node * last = 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(&last, val);
  }

  printf("Linked List: ");
  print_list(last->next);
}

This is the output of the program.

Insert at the front of a circular linked list output

Insert at the End

Inserting at the end is exactly same as inserting at front. You have to make the newly inserted node the last node. Just point the last pointer to the new node.

/*Insert an element at the end of the list*/
void insert_end(struct node **last, int value) {
  /*Allocating memory for the new node*/
  struct 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;
    
  if(*last == NULL) {
    /*List is empty*/
    *last = new_node;
    new_node->next = new_node;
    return;
  }

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

  /*Pointing last node to new node.*/
  (*last)->next = new_node;
  
  /*Make the new node last node*/
  *last = new_node;
}

Inserting in the middle of a circular linked list is same as inserting into a regular linked list.

The post Circular Linked List in C appeared first on QnA Plus.

Execute User Defined Function Before Main() in C

$
0
0

We know that the main() function is the entry point of a program. This is generally true. But we can execute some functions even before main() starts.

In some circumstances, you might need to execute an user defined function before main(). For example, if you are creating a library, you might need to initialize certain data structures before any function of your library is called. You can certainly define an initialize() function. But the user of that library would have to remember to call this function. Better solution would be to execute initializing function during library load, even before the main() starts.

Similarly, you’ll need some function for clean up after main() returns.

Using __attribute__ ((constructor)) / ((destructor))

GNU C compiler has a feature to mark functions that would be executed before or after the main() function.

  • We can use __attribute__ ((constructor)) to mark a function constructor.
  • We can use __attribute__ ((destructor)) to mark a function as destructor.

The constructor functions will be executed before main() and the destructors after main().

The Program

#include<stdio.h> 

void FunBeforeMain(void) __attribute__ ((constructor)); 

void FunAfterMain(void) __attribute__ ((destructor)); 


void FunBeforeMain(void) 
{ 
	printf("FunBeforeMain() called.\n"); 
} 

void FunAfterMain(void) 
{ 
	printf("FunAfterMain called.\n"); 
} 

int main(void) 
{ 
	printf("main() started.\n"); 
	printf("main() exited.\n");
  return 0; 
}

We marked “FunBeforeMain()” with __attribute__ ((constructor)) and “FunAfterMain()” with __attribute__ ((destructor)).

Here is the output of the program.

function before main()

From this output, we can see that the “FunBeforeMain()” is executed before main() starts and “FunAfterMain()” after main() returns.

The special sections, .ctors and .dtors of ELF (Executable and Linkable Format), contain the function references marked with constructor and destructor attributes. When the program (binary or shared library) gets loaded, the program loader checks whether any function reference is present in .ctors section. If so, called those functions. Similar thing happens when the program is unloaded. Function references present in .dtor section are called after main() exits.

We can mark multiple functions as constructor or destructor.

#include<stdio.h> 

void FunBeforeMain1(void) __attribute__ ((constructor)); 
void FunBeforeMain2(void) __attribute__ ((constructor)); 

void FunAfterMain1(void) __attribute__ ((destructor)); 
void FunAfterMain2(void) __attribute__ ((destructor)); 

void FunBeforeMain1(void) 
{ 
	printf("FunBeforeMain1() called.\n"); 
}
 
void FunBeforeMain2(void) 
{ 
	printf("FunBeforeMain2() called.\n"); 
}

void FunAfterMain1(void) 
{ 
	printf("FunAfterMain1 called.\n"); 
}

void FunAfterMain2(void) 
{ 
	printf("FunAfterMain2 called.\n"); 
}

int main(void) 
{ 
	printf("main() started.\n"); 
	printf("main() exited.\n");
  return 0; 
}

Output of the above program.

multiple functions as constructor and destructor

One thing to notice in this output is that the destructors are called in reverse order.

The post Execute User Defined Function Before Main() in C appeared first on QnA Plus.

Execute User Defined Function before Main() in C++

$
0
0

In the previous article, we saw how to execute user defined function before main() in C. In C++ also we can use same mechanism to execute function before main. Here we’ll explore other options in C++.

Execute Function before Main() By Creating Global Object

  1. Define a class. Call an user defined function from the class constructor.
  2. Create a global object of that class.
#include <iostream>

void FunBeforeMain() {
  std::cout << "FunBeforeMain() called." << std::endl;
}

class C {
  public:
    C() {
      FunBeforeMain();
    }
};

C oc;

int main() {
  std::cout << "Main started." << std::endl;
  return 0;
}

Here is the output of this program.

Call function before main()

We can see from this output that the user defined function, FunBeforeMain(), was called even before the main() function started.

In C++, global variables are initialized before main() starts. So as part of global object (oc) initialization, the C class constructor is called. The constructors are also like any other user defined functions. We called the user defined function from the constructor.

By Initializing Static Variable with Return Value of a Function

If we initialize a class static variable with the return value of a user defined function, that function would be called before main().

  1. Declare a class with a static variable.
  2. Initialize the static variable with a user defined function.
#include <iostream>

int FunBeforeMain() {
  std::cout << "FunBeforeMain() called." << std::endl;
  return 0;
}

class C {
  public:
    static int static_variable;
};

int C::static_variable = FunBeforeMain();

int main() {
  std::cout << "Main started." << std::endl;
  return 0;
}

Static variables are like global variables. They are initialized before main(). If we initialize a static variable with the return value of a function, the function would be called as part of initialization. Here the static_variable is initialized with the return value of FunBeforeMain(). So FunBeforeMain() is called before main().

The out of this program would be exactly same as the first one.

Initializing Global Variable with Return Value of a Function

Like the previous example, instead of initializing a static variable, we can initialize a global variable with the return value of a function. We’ll have the same effect.

#include <iostream>

int FunBeforeMain() {
  std::cout << "FunBeforeMain() called." << std::endl;
  return 0;
}

class C {
  public:
    static int static_variable;
};

int C::static_variable = FunBeforeMain();

int main() {
  std::cout << "Main started." << std::endl;
  return 0;
}

The post Execute User Defined Function before Main() in C++ appeared first on QnA Plus.

Delete N-th Node from End of a Linked List

$
0
0

In the previous article, we saw how to delete the N-th node of a linked list from the beginning of the list. Here we’ll see how to delete N-th node from the end. N starts with 0. Deleting 0-th node from end means deleting the last node.

Logic to Delete the N-th Node from End of a Linked List

  1. If head points to NULL, then return. The list is empty.
  2. Point 2 pointers, prev and end to head.
  3. Move end pointer to (N+1)-th position.
  4. Move prev and end pointers until end becomes NULL.
  5. If end becomes NULL before (N+1)-th iteration, return. Enough nodes do not exist.
  6. Delete the next node of prev. and point prev where the deleted node was pointing.

The Program

/*File: test.c*/

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

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

/*Delete the n-th node of a linked list from end.*/
void delete_nth_node_from_end(struct node **head, int n) {
  struct node *prev = NULL, *end = NULL;
  struct node *del_node = NULL;
  int i = 0;
  /*Linked list does not exist or the list is empty*/
  if (head == NULL || *head == NULL) return;
  
  /*Storing the head to a temporary variable*/
  prev = *head;
  end = *head;
  
  /*Placing the end pointer to (N+1)-th position...*/
  for (i = 0; i <= n+1; i++) {
    if (end == NULL) break;
    end = end->next;
  }
  
  /*Enough nodes not present.*/
  if (i < n+1) return;

  /*Special case: we have to delete the first node.*/
  if (i == n+1 && end == NULL) {
    *head = (*head)->next;
    free(prev);
    return;
  }
  
  /*Move start and end until end becomes NULL.*/
  while (end) {
    end = end->next;
    prev = prev->next;
  }
  
  /*Node to be deleted.*/
  del_node = prev->next;
  
  /*De-link the n-th node*/
  prev->next = prev->next->next;
  
  free(del_node);
}

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

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

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

/*Insert a node at the end of the list*/
void insert_end(struct node **head, int value) {
    
    struct node* new_node = NULL;
    struct node* tmp = *head;

    /*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;
    new_node->next = NULL;

    /*If the list is empty, the new node becomes the first node.*/
    if (*head == NULL) {
      *head = new_node;
      return;
    }
    
    /*Reaching to the last node...*/
    while(tmp->next) tmp = tmp->next;
    
    tmp->next = new_node;
}

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

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

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

    printf("Initial Linked List: ");
    print_list(head);
    
    printf("Enter a position: ");
    scanf("%d", &n);
    
    delete_nth_node_from_end(&head, n);
    
    printf("Linked List after deleting %d-th node from end: ", n);
    print_list(head);
}

This program first takes input of a linked list and a position (N). It prints the list before and after deleting the N-th node from end. The delete_nth_node_from_end() function is called to delete the N-th node from end. Here is the output of the program.

The post Delete N-th Node from End of a Linked List appeared first on QnA Plus.


C Program to Check Whether Two String are Equal

$
0
0

Here we’ll see how to check whether two strings are equal. C string (string.h) library already provides a function to do that.

Using strcmp()

  1. Take two strings as input (say, s1 and s2).
  2. Call strcmp() with two input strings.
  3. If strcmp() returns 0, the strings are equal, otherwise, not.
#include <stdio.h>
#include <string.h>

int main() {
  char s1[100], s2[100];
  printf("Enter string1: ");
  gets(s1);
  printf("Enter string2: ");
  gets(s2);
  
  if (strcmp(s1, s2) == 0) {
    printf("Two strings are equal.\n");
  } else {
	printf("Two strings are not equal.\n");
  }
  return 0;
}

Here is the output of the program.

C Program to check two strings are equal

Not Using strcmp()

In the above example, we used the library function, strcmp(), to compare the strings. But we can write our own function for the same purpose.

Logic to Check Whether Two Strings are Equal

  1. Traverse two strings from the 0-th position until the character of at least one string is NULL (‘\0’).
  2. If the characters of a particular position of two strings are not equal, return 0. Strings are not equal.
  3. After traversal, if the characters of the current position of both strings are NULL (‘\0’), return 1. Strings are equal. Otherwise, return 0.

Here is the program.

#include <stdio.h>

/*
Returns 1 if two input strings are equal, otherwise, 0.
*/
int is_string_equal(char* s1, char* s2) {
  int i = 0;
  while (s1[i] != '\0' && s2[i] != '\0') {
    if (s1[i] != s2[i]) return 0; /*i-th character is different*/
    i++;
  }
  
  if (s1[i] == '\0' && s2[i] == '\0') return 1;

  return 0;
}

int main() {
  char s1[100], s2[100];
  printf("Enter string1: ");
  gets(s1);
  printf("Enter string2: ");
  gets(s2);
  
  if (is_string_equal(s1, s2)) {
    printf("Two strings are equal.\n");
  } else {
	printf("Two strings are not equal.\n");
  }
  return 0;
}

Here the is_string_equal() function returns 1 if two inpur strings are equal, otherwise, returns 0.

In the above programs, the string comparision is case sensitive. That means, ‘QnAPlus’ and ‘qnaplus’ are not equal. Here is how we can compare strings in case insensitive way.

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

C Program to Check Whether Two Strings are Equal in Case Insensitive Way

$
0
0

In the previous article, we saw how to check whether two strings are equal. But there the comparision was case sensitive. That means, ‘QnAPlus’ and ‘qnaplus’ are not equal. Here we’ll see how we can compare strings in a case insensitive way.

There is no library function in standard C to compare strings in case insensitive way. So we have to write our own function. Here is the program.

#include <stdio.h>

/*
Returns 1 if two input strings are equal (case insensitive), otherwise, 0.
*/
int is_string_equal(char* s1, char* s2) {
  int i = 0;
  while (s1[i] != '\0' && s2[i] != '\0') {
    if (toupper(s1[i]) != toupper(s2[i])) return 0; /*i-th character is different*/
    i++;
  }
  
  if (s1[i] == '\0' && s2[i] == '\0') return 1;

  return 0;
}

int main() {
  char s1[100], s2[100];
  printf("Enter string1: ");
  gets(s1);
  printf("Enter string2: ");
  gets(s2);
  
  if (is_string_equal(s1, s2)) {
    printf("Two strings are equal.\n");
  } else {
	printf("Two strings are not equal.\n");
  }
  return 0;
}

This program takes two strings as input and calls the is_string_equal() function to check whether they are equal. The the two input strings are eqaul, then the is_string_equal() function returns 1, otherwise, 0.

Here is the output of the program.

Two strings are equal (case insensitive)

The post C Program to Check Whether Two Strings are Equal in Case Insensitive Way appeared first on QnA Plus.

C Program to Reverse an Array

$
0
0

Here we’ll see how we can write a C program to reverse an array. If an array is ’43 23 45 11 8 54 89′, then after reversal it will become ’89 54 8 11 45 23 43′. We’ll start will a simple approach – will reverse the array with help of an another array. We’ll copy the last element of the original array to the first element of the new array. Similarly, second last will be copied to the second element and so on. After we complete this process, the new array will have all the elements in reversed order. Then we’ll replace the original array with the new reverse array.

C Program to Reverse Array

#include <stdio.h>

void reverse_array(int* arr, int size) {
  int i;
  int arr1[124];

  /*Coping the array into a temporary array in reverse order...*/
  for (i = 0; i < size; i++) {
	arr1[i] = arr[size -1 - i];
  }
  
  /*Copying the reverse array into the original one...*/
  for (i = 0; i < size; i++) {
	arr[i] = arr1[i];
  }
}

int main() {
  int n;
  int i;
  int arr[128];
  printf("Enter number of elements: ");
  scanf("%d", &n);
  
  /*Taking the array as input from user...*/
  for (i = 0; i < n; i++) {
    printf("Enter %d-th element: ", i);
    scanf("%d", (arr+i));
  }
  
  /*Printing the input array...*/
  printf("The input array: ");
  for (i = 0; i < n; i++) {
    printf(" %d", arr[i]);
  }
  printf("\n");
  
  reverse_array(arr, n);
  
  /*Printing the array after reversing...*/
  printf("The reversed array: ");
  for (i = 0; i < n; i++) {
    printf(" %d", arr[i]);
  }
  printf("\n");
  return 0;
}

This program first takes input of an array and passes that array to the reverse_array() function. The reverse_array() function reverses the array using the logic mentioned above.

Here is the output.

reverse an array

The above reverse_array() function works well except it is bit inefficient. It takes help of another array, that means requires more memory. It also traverses the array twice.

Improved Logic

We can reverse the array without using any other array. Also we don’t have to traverse the array twice. We can swap the first element and the last element, second and the second last element and so on. We have to iterate upto the middle element.

Here is the improved reverse_array() function.

void reverse_array(int* arr, int size) {
  int i, tmp;

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

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

C Program to Insert an Element in an Array

$
0
0

Here we’ll see how to insert an element in an array at a particular position, after or before an existing element. If we insert an element in an array, all the elements, after the inserted position, need to be shifted to the next position.

Inserting at a Particular Position

We’ll start by inserting a new element at a particular position of the array.

#include <stdio.h>

void insert_at(int val, int pos, int* arr, int size) {
  int i;
  
  /*If the insert position is greater than the array size, insert at the end of the array*/
  if (pos >= size) {
    arr[size] = val;
    return;
  }
 
  for (i = size; i > 0; i--) {
    arr[i] = arr[i-1];
    if (pos == i-1) {
      arr[i-1] = val;
      break;
    }
  }
}

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

int main() {
  int i, n, val, pos;
  int arr[128];
  printf("Enter number of elements: ");
  scanf("%d", &n);
  
  /*Taking the array as input from user...*/
  for (i = 0; i < n; i++) {
    printf("Enter %d-th element: ", i);
    scanf("%d", (arr+i));
  }
  
  /*Printing the input array...*/
  printf("The input array: ");
  print_array(arr, n);
  
  printf("Enter a value to be inserted: ");
  scanf("%d", &val);
  printf("Enter position: ");
  scanf("%d", &pos);
  
  insert_at(val, pos, arr, n);
  
  /*Printing the array after insertion...*/
  printf("The array after insertion: ");
  print_array(arr, n+1);
  return 0;
}

This program first takes an array of integers as input and prints that. Then it takes input of the new element to be inserted and the position. It then calls the insert_at() function to insert the new element into the existing array.

The insert_at() function takes the new element and its postion and the existing array as input. If the position (pos) is greater than the array size, then it inserts the new element at the end of the array and returns. If not a loop starts from the end of the array. The iterrator, i, starts from size, where last element position is (size -1). In every iteration, (i-1)-th element is copied to i-th position. If the position of the new elemet is (i-1), then the new element is copied to that position and the loop terminates.

After calling the insert_at() function, the program prints the new array. After the insertion, the array size increases by one. That’s why, it prints (n+1) elements.

Insert an element in an array at a particular position

From this output, we can see that a new element (100) is inserted at 4-th (starting from 0) position.

Inserting After an Existing Element

Here we’ll see how to insert a new element after an existing one. For example, if we want to insert the new element, 100, after the existing element 22, then 1oo will be insterted after all occurences of 22. That means array size can increase by more than one.

#include <stdio.h>

void insert_at(int val, int pos, int* arr, int size) {
  int i;
  
  /*If the insert position is greater than the array size, insert at the end of the array*/
  if (pos >= size) {
    arr[size] = val;
    return;
  }
 
  for (i = size; i > 0; i--) {
	arr[i] = arr[i-1];
	if (pos == i-1) {
	  arr[i-1] = val;
	  break;
	}
  }
}

int insert_after(int val, int after, int* arr, int size) {
  int i;
  int size1 = size;
 
  for (i = 0; i < size1; i++) {
	if (arr[i] == after) {
	  insert_at(val, i+1, arr, size1);
	  size1++;
	}
  }
  return size1;
}

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

int main() {
  int i, n, val, after, size;
  int arr[128];
  printf("Enter number of elements: ");
  scanf("%d", &n);
  
  /*Taking the array as input from user...*/
  for (i = 0; i < n; i++) {
    printf("Enter %d-th element: ", i);
    scanf("%d", (arr+i));
  }
  
  /*Printing the input array...*/
  printf("The input array: ");
  print_array(arr, n);
  
  printf("Enter a value to be inserted: ");
  scanf("%d", &val);
  printf("Insert after: ");
  scanf("%d", &after);
  
  size = insert_after(val, after, arr, n);
  
  /*Printing the array after insertion...*/
  printf("The array after insertion: ");
  print_array(arr, size);
  return 0;
}

Here we’ll use the insert_at() function. The new insert_after() function first finds the position where the new element to be inserted at. Then it calls the insert_at() function. The loop in insert_after() function checks whether the current element (arr[i]), matches the value after which the new element will be inserted. If it matches, then the insert_at() function is called with (i+1). The new element will be inserted at (i+1)-th position.

For every insert_at() call, then array size (size1) increases by one. After looping through all the elements, the insert_after() function returns the new array size. The main() function uses the new array size to print all elements in the array.

Insert an element in array after an existing element

In this output, the new element 100 is inserted after 22. As there were 3 occurences of 22, the new element was inserted thrice in the array after 22.

Inserting After an Exiting Element

Inserting the new element before an existing one is very similar to the previous example. The insert_before() function is shown here.

int insert_before(int val, int before, int* arr, int size) {
  int i;
  int size1 = size;
 
  for (i = 0; i < size1; i++) {
	if (arr[i] == before) {
	  insert_at(val, i, arr, size1);
	  size1++;
	  i++;
	}
  }
  return size1;
}

This function is similar to the insert_after() function except it call the insert_at() function with i instead of (i+1). One more differnce – the iterator, i, is also increased after insert_at() call. Because after insertion, the i-th element will move the (i+1)-th position. So we need to increment the iterator by 2 in this case. Otherwise, the checking (arr[i] == before) will continue to be true and the loop will become infinte. It will eventually lead to program crash.

Insert an element in an array before an existing element

In this output we can see the new element 100 is inserted before all three accurences of 22.

Note: In all above examples, it is assumed that the array has enough allocated space (memory) to fit the new elements.

The post C Program to Insert an Element in an Array appeared first on QnA Plus.

C Program to Delete Element from an Array

$
0
0

Here we’ll see how to delete an element of a particular position from an array. Deleting element means left-shifting the right elements starting from the position.

#include <stdio.h>

void delete_pos(int* arr, int size, int pos) {
  int i;
  
  /*If the position is greater than the array size, deletion not possible*/
  if (pos >= size) {
    printf("Deletion not possible.\n");
    return;
  }
 
  for (i = pos; i < size - 1; i++) {
    arr[i] = arr[i+1];
  }
}

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

int main() {
  int i, n, pos;
  int arr[128];
  printf("Enter number of elements: ");
  scanf("%d", &n);
  
  /*Taking the array as input from user...*/
  for (i = 0; i < n; i++) {
    printf("Enter %d-th element: ", i);
    scanf("%d", (arr+i));
  }
  
  /*Printing the input array...*/
  printf("The input array: ");
  print_array(arr, n);
  
  printf("Enter position: ");
  scanf("%d", &pos);
  
  delete_pos(arr, n, pos);
  
  /*Printing the array after deletion...*/
  printf("The array after deletion: ");
  print_array(arr, n-1);
  return 0;
}

The above program first takes the array as input and the position of an element to be deleted. Then it prints the array before and after deleting the element. The delete_pos() function is called to delete an element from a particular position.

Here is the output of the program.

delete element from an array

Read also: Insert element in an array.

The post C Program to Delete Element from an Array appeared first on QnA Plus.

C Program to Remove All Occurrences of a Number from an Array

$
0
0

In the previous article we saw how to remove an element of a particular position from an array. Here we’ll see how we can remove all occurrences of a number. For example, if an array has the number 100 three times, all three ocurrences of 100 will be removed. The holes created by the removal of three 100’s will be filled by other numbers in the array. As a result, the size of the array will be reduced by three.

Here is the C program.

#include <stdio.h>

int remove_val(int* arr, int size, int val) {
  int i, count = 0;
 
  for (i = 0; i < size; i++) {
    if (arr[i + count] == val) count++;
    arr[i] = arr[i+ count];
  }
  
  return size - count;
}

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

int main() {
  int i, n, val, r;
  int arr[128];
  printf("Enter number of elements: ");
  scanf("%d", &n);
  
  /*Taking the array as input from user...*/
  for (i = 0; i < n; i++) {
    printf("Enter %d-th element: ", i);
    scanf("%d", (arr+i));
  }
  
  /*Printing the input array...*/
  printf("The input array: ");
  print_array(arr, n);
  
  printf("Enter a value to remove: ");
  scanf("%d", &val);
  
  r = remove_val(arr, n, val);
  
  /*Printing the array after deletion...*/
  printf("The array after removing %d: ", val);
  print_array(arr, r);
  return 0;
}

This program first takes an array as input and prints the array. Then it takes the number to be removed as input. It calls the remove_val() function to remove a particular number. This function returns the new size of the array. The it prints the array with the new size.

Here is the output of the program.

Remove all occurrences of a number from an array

The post C Program to Remove All Occurrences of a Number from an Array appeared first on QnA Plus.

C Program to Remove all Occurences of a Character from a String

$
0
0

Here we’ll see how to remove all occurences of a character from a string. For example, if we remove the character ‘o‘ from the string “The quick brown fox jumps over the lazy dog“, the result will be “The quick brwn fx jumps ver the lazy dg“. All four occurneces of ‘o’ removed from the string. The other characters will fill the holes created by removal of ‘o’.

Here is the C program.

#include <stdio.h>

void remove_char(char* str, char ch){
  int i = 0, count = 0;
  
  while (str[i + count] != '\0') {
    /*Skipping the matched character...*/
    if (str[i + count] == ch) count++;
    
    str[i] = str[i + count];
    i++;
  }
  str[i] = '\0';
}

int main() {
  char str[256], ch;
  printf("Enter a string: ");
  fgets(str, sizeof(str), stdin);
  printf("Enter a character to remove: ");
  ch = getchar();
  
  remove_char(str, ch);
  printf("The string after removing %c: %s\n", ch, str);
  return 0;
}

The above program takes a string and a character as input. Then it call the remove_char() function to remove the character and prints after removal.

Here is the output.

remove all occurences of a character from a string

The post C Program to Remove all Occurences of a Character from a String appeared first on QnA Plus.


C Program to Replace All Occurrences of a Character by Another One in a String

$
0
0

Here we’ll see how to replace all occurrences of a character by another one in a string.

Read also: C program to remove all occurrences of a character.

#include <stdio.h>

void replace_char(char* str, char find, char replace){
  int i = 0;
  
  while (str[i] != '\0') {
    /*Replace the matched character...*/
    if (str[i] == find) str[i] = replace;
    
    i++;
  }
}

int main() {
  char str[256], find, replace;
  printf("Enter a string: ");
  fgets(str, sizeof(str), stdin);
  printf("Character to replace: ");
  find = getchar();
  getchar();
  printf("Replace with: ");
  replace = getchar();
  
  replace_char(str, find, replace);
  printf("The string after replacing %c with %c: %s\n", find, replace, str);
  return 0;
}

This program first takes a string as input, then two characters. First character will be replaced by the second one. The replace_char() function replaces the find character with the replace character. It has a loop that iterates through all the characters of the input string, str. If the character of particular position matches with find, that position of the string is assigned with replace.

Here is the output of the program.

Replace all occurrences of a character

The post C Program to Replace All Occurrences of a Character by Another One in a String appeared first on QnA Plus.

C Program to List All Files in a Directory

$
0
0

Listing all files in a directory is a very common programming requirement. Here we’ll see how to read and display all file names in a directory using C directory entry (dirent) library.

#include <dirent.h>
#include <stdio.h> 

int main(void) {
  DIR *dir;
  struct dirent *entry;
  dir = opendir(".");
  if (dir == NULL) {
    printf("Failed to open directory.\n");
    return 1;
  }
  while ((entry = readdir(dir)) != NULL) {
    if(entry->d_type != DT_DIR) {
      printf("%s\n", entry->d_name);
    }
  }
  closedir(dir);
  return 0;
}

This program first opens the current directory (“.”) using opendir() function. In a loop, each entry in the directory is read using readdir() function and printed if its type is not directory.

$ ls
 file1.txt  file2.txt  file3.txt  subdir1  subdir2

The current directory above contains 3 text files and two subdirectories. If we run our program in this directory, we’ll see the following output.

$ ./test
 file1.txt
 file2.txt
 file3.txt

This output does not contain the files of the subdirectories.

Read also: List all files including subdirectories.

The post C Program to List All Files in a Directory appeared first on QnA Plus.

C Program to List All Files Including Subdirectories

$
0
0

In the previous article, we saw how to list all files in a particular directory. That program does not display the files of the subdirecties. Here we’ll see how to display the files of the current direcory and of the subdirectories. The directory stucture could be arbitarily nested. The program here will display the files in a tree structure.

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

void list_dir(char *path, int indent) {
  DIR *dir;
  struct dirent *entry;
  dir = opendir(path);
  
  if (dir == NULL) {
    printf("Failed to open directory.\n");
    return;
  }
  while ((entry = readdir(dir)) != NULL) {
    if(entry->d_type == DT_DIR) {
      if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) {
        printf("%c%s\n", indent2, '-', entry->d_name);
        char *new_path = (char *)malloc(strlen(path) + strlen(entry->d_name) + 1);
        sprintf(new_path, "%s/%s", path, entry->d_name);
        list_dir(new_path, indent + 1);
        free(new_path);
      }
      } else {
        printf("%c%s\n", indent2, '-', entry->d_name);
      }
    }
    closedir(dir);
}

int main(void) {
  printf("Current directory structure:\n");
  list_dir(".", 1);
  return 0;
}

The list_dir() recursive function displays all files in the current directory. And for all directories inside the current directory, this function calls itself recursively.

$ ls
 file1.txt  file2.txt  file3.txt  subdir1  subdir2

The above current directory has 3 files and two subdirectories. If we run the program in this directory we’ll see the following putput.

$ ./test
 Current directory structure:
  -file1.txt
  -file2.txt
  -file3.txt
  -subdir1
    -file1.txt
  -subdir2
    -file1.txt
    -file2.txt

The post C Program to List All Files Including Subdirectories appeared first on QnA Plus.

C Program to Count Occurrences of Each Element in an Array

$
0
0

Here we’ll see how to write C program to count occurrences of each element in an array. The C program will check how many times a particular integer occurs in the array.

#include <stdio.h>

#define MAX_ARRAY_LEN 1024

int main(){
  int arr[MAX_ARRAY_LEN];
  int counter[MAX_ARRAY_LEN];
  int len = 0;
  int i, j;
  
  printf("Enter the array size: ");
  scanf("%d", &len);

  printf("Enter array elements: ");
  for (i = 0; i < len; i++) {
    scanf("%d", &arr[i]);
    counter[i] = -1; /* Marking as not visisted. */
  }

  for (i = 0; i < len; i++) {
    
    /* i-th element is already visited/counted. */
    if (counter[i] == 0) continue;
    
    counter[i] = 1;
    for (j = i + 1; j < len; j++) {
      if(arr[i] == arr[j]) {
        counter[i]++;
        counter[j] = 0;
      }
    }
  }
  
  for (i = 0; i < len; i++) {
    if (counter[i] == 0) continue;
    printf("%d occured %d times.\n", arr[i], counter[i]);
  }

  return 1;
}

This program first takes the array size and the array elements as input. It maintains another array of same size to keep the elements counters / occurrences.

For each array element, the corresponding counter array element is initialized as -1 to mark as non-visited.

The outer loop iterates for every element of the array. If the corresponding counter [counter[i]] is 0 (means already visited), it skips that element. The inner loop scans the next array elements.

If a match is found, the corresponding counter array element is set to 0 to mark as visited. And the counter is incremented by 1.

At the element, for all elements with non-zero counter value is printed with their corresponding occurrence counter.

Here is sample output.

$ cc test.c -o test
$ ./test
Enter the array size: 10
Enter array elements: 2 32 5 45 6 2 2 45 32 32
2 occured 3 times.
32 occured 3 times.
5 occured 1 times.
45 occured 2 times.
6 occured 1 times.

The post C Program to Count Occurrences of Each Element in an Array appeared first on QnA Plus.

C Program to Find the Longest Word in a String

$
0
0

A word is a consecutive non-whitespace character set. The C program here will find out the longest word in a given string. If multiple words are present with the same length of the longest one, it will print the first one.

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

#define MAX_STRING_LEN 1024

int main(){
  char str[MAX_STRING_LEN];
  char longest_str[MAX_STRING_LEN];
  int len;
  int i, index = 0;
  int max_wlen = 0, wlen = 0;
  
  printf("Enter a string: ");
  gets(str);
  
  len = strlen(str);
  
  for (i = 0; i <= len; i++) {
  
    if (str[i] != ' ' && str[i] != '\0') {
      wlen++;
      continue;
    }
    
    /* space or end of string */
    if (wlen > max_wlen) {
      max_wlen = wlen;
      index = i - max_wlen;
    }
    
    wlen = 0;
  }
  
  for (i = 0; i < max_wlen; i++) {
    longest_str[i] = str[index+i];
  }
  
  longest_str[i] = '\0';
  
  printf ("Longest word: %s.\n", longest_str);
  printf ("Longest word length: %d.\n", max_wlen);
  return 1;
}

This program takes a string as input. The first ‘for‘ loop traverses all the characters in the string. This loop has one extra iteration than the length of the string – to consider the last word.

The wlen variable tracks the current word length and max_wlen tracks the longest word length so far.

For every non-whitespace character, the current word length, wlen, is increased by 1.

A whitespace character is considered as a possible end of a word – unless the previous character is also a whitespace.

If a whitespace character is encountered and the current word is longer than the longest word so far (wlen > max_wlen), current word length is set as the longest one. The index variable is set as the starting index of the longest word so far. For every whitespace character wlen is reset to o – to start a fresh count for the next word.

When the first loop ends, the index becomes the starting index of the longest word. And max_wlen becomes the length of the longest word.

The second ‘for‘ loop copies the longest word to another string, longest_str. At the end the program prints the longest word with it length.

The program output:

$ ./test
Enter a string: Optimism is an occupational hazard of programming
Longest word: occupational.
Longest word length: 12.

The post C Program to Find the Longest Word in a String 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>